Who’s On Phirst

Official blog of Phurnace Software.

Tag >> Groovy

Posted by: Wesley Willard on

To a non-geek, spending a weekend in hotel conference rooms listening to presentations on the latest technologies in software development might make them beg, "just shoot me now, please". But to someone interested in keeping abreast of these sorts of things, for both company and personal reasons, it was a very nice way to do just that. Plus, it was hot as hell outside, the neighborhood pool is even hot, and the lake is just too far away.

The Lone Star Symposium was held this past weekend here in Austin, and it was a great show. The lack of vendor presence at these conferences allow software developers to focus on the technology itself. The people who put this conference together go out of their way to provide all the amenities to the attendees, such as good food, snacks, not to mention some of the best industry experts out there. With regard to the experts, I am always pleased to find not only those who write about the technologies at this show, but also those who have had a hand in developing them. A case in point, the presenter for the Spring Framework was Keith Donald, one of principals and founders.

It's always a shame that you can't make it to all the sessions in this type of conference, but you generally can't go wrong with any selection. Just to sort of sum up, the hottest topics this year were the ones concerning dynamic languages, such as Groovy, and it's related framework, Grails. Also, Spring continues to be THE overarching framework for J2EE development.

My favorite session, though, was one by Neil Ford, titled "Productive Programmer: Acceleration & Automation". I am a sucker for cool command line tools, and he talked about such great productivity enhancers such as Auto-Hot Key, which allows you to define (and redefine) hot keys in Windows, and clcl, which allows you to maintain multiple clipboards. I am very keyboard-oriented, and these tools will allow me to stay away from my carpal-inducing mouse.

Next time one of these conferences makes its way near you, check it out. Especially if its a hot summer weekend!

In Spring FrameworkGroovy
Comment (0) Read More...


Posted by: Wesley Willard on

While Robert Reeves is correct in his assessment that scripting can be evil, especially in cases where scalable and durable automation is needed (like deployments of apps),there are occasions where a script can definitely serve as a useful problem-solving tool. A script can act as another way to view an application's data, allowing the developer to verify the state of the data independently. Creating a script does not generally require the same amount of time to code/compile/edit as a regular programming language, thus can be more quickly developed in an iterative fashion. Also, since scripting languages are not used as often to create commercial applications as are programming languages like Java, a script can be used to prototype some experimental functionality, without danger that the prototype will escape the building.

I have resisted taking the time to learn much about the many scripting languages which have been created in the last few years, but Groovy is one which, as a Java developer, has really caught my eye. It is built on Java, but provides additional features which have been inspired by other languages such as Ruby and Objective-C.

I find Groovy to be my current scripting language of choice for a few simple reasons:

  • Java-like syntax is extremely easy to pick up
  • Ability to leverage the many powerful Java APIs
  • Useful built-in features like Categories, which enable dynamic extension of any class

In the following code, I’ll demonstrate some of these things. I will be making a remote connection to a JBoss Application Server in order to retrieve MBean attributes, as well as invoke operations on the MBean.

First, I will import some classes, and make a connection to the server:


package com.groovy

import javax.management.ObjectName
import javax.management.MBeanServerConnection
import javax.naming.InitialContext
import org.apache.xpath.XPathAPI
import groovy.xml.dom.DOMCategory
import org.w3c.dom.Element

def
password = ""
def initialContextFactory = "org.jboss.security.jndi.
JndiLoginInitialContextFactory"
def JMX_INVOKER_RMI_ADAPTOR = "jmx/invoker/RMIAdaptor"
def port = 1099
def host = "localhost"
def username = ""
def password = ""
def initialContextFactory = "org.jboss.security.jndi.
JndiLoginInitialContextFactory"

//
// Connect to JBoss
//
Properties props = new Properties(System.getProperties())
props.put("java.naming.factory.initial", initialContextFactory)
props.put("java.naming.provider.url", host + ":" + port)
props.put("java.naming.security.principal", username)
props.put("java.naming.security.credentials", password)
def ctx = new InitialContext(props)
Object obj = ctx.lookup(JMX_INVOKER_RMI_ADAPTOR)
def mbsc = (MBeanServerConnection) obj
ctx.close()

Once I have made my connection, I will then use it to invoke an operation on a JBoss MBean.


//
// Create a class to be used as a String Category
// StringCategory extends the String class with
// a new method that splits a String at the newline delimiter
//
class MyStringCategory {
public static List splitOnNewLine(String string) {
return string.tokenize("\n")
}
}
//
// Invoke the operation listDeployedURLs on the Groovy MBean
// Use the category defined above to split up the return string
//
use (MyStringCategory) {
def deploymentScanner =
new GroovyMBean(mbsc, "jboss.deployment:flavor=URL,
type=DeploymentScanner")
def deployedURLs = deploymentScanner.listDeployedURLs()
def deployedList = deployedURLs.splitOnNewLine()
deployedList.each( { println it } )
}

This snippet illustrates a couple of interesting Groovy features. The class MyStringCategory is an example of a Groovy Category. A Category in Groovy is a class which defines methods which can extend any specified class. In the example, the method splitOnNewLine is a category method on the Groovy class String, due to the fact that the method is static, and the first argument (or target) is of type String. This method can be called on any instance of a String, and will return a List containing one entry per new line found in the String. To enable the category method to be called, the call must be enclosed in a use statement, which references the name of the category.

Also notice that I have created an instance of a GroovyMBean, constructing it using the server connection and the name of the JBoss MBean. The GroovyMBean is a built-in Groovy class, which allows an MBean to be used as a regular Groovy object. I use this object to call the listDeployedURLs() method on the JBoss MBean, which returns a String representation of the currently deployed URLs on the server. I then use my splitOnNewLine() category method to create a List, which can then be iterated.

The next snippet of code illustrates how easy it is to make use of an existing Java API within Groovy.

 


//
// Create GroovyMBean to retrieve the JBoss Mail Service
// configuration information, which is returned by JBoss
// as an XML Element object
//
def mailBean = new GroovyMBean(mbsc, "jboss:service=Mail")
def configurationXML = mailBean.Configuration

//
// Use the Apache XPath API to select the nodes,
// and iterate through them with a closure
//
def nodeList = XPathAPI.selectNodeList(configurationXML,
"//property[@name]")
def printNode = { println it.getAttribute("name") + "=" +
it.getAttribute("value")
nodeList.each(printNode)

After the creation of another GroovyMBean, the Apache XPath API is used to select the nodes in the returned XML Element. The resulting NodeList is then iterated. Using an existing Java API in this fashion is just as simple as importing the appropriate class, and then calling its methods.

The final part of this example uses another category, MyDOMCategory, in conjunction with a built-in Groovy category, DOMCategory, to process the same XML Element. The call to list() is a category method which transforms a NodeList object into a List object. The List object is iterated, and its attributes are retrieved using the Element category method attribute(Element node, String attrName) to retrieve the name and value attributes.

 


//
// The class MyDOMCategory extends the Element class
// to return the value for the specified attribute
//
class MyDOMCategory {
static String attribute(Element node, String attrName) {
return node.attributes[attrName]
}
}

//
// Use Groovy Categories to iterate through the NodeList
//
use (DOMCategory, MyDOMCategory) {
configurationXML."property".list().each(
{ println "MyDOMCategory: " + it.attribute("name") + "="
+ it.attribute("value") } )
}

Hopefully, these short snippets of code illustrate the simplicity that I think makes Groovy a very attractive option for scripting use in the Java development world. I would highly recommend it as a useful addition to your software developer's toolkit.

In ScriptsScripting LanguageGroovy
Comment (0) Read More...