Tuesday, October 7, 2008

Scripting Ant tasks with BSF

Today I wrote a couple of custom Ant tasks in Groovy, using the Scriptdef optional task. I had never used scripting languages within Ant (nor was I familiar with task development for that matter), but it proved to be really quick and straightforward.

Here is a very simple example: I wanted to configure the load order for a Weblogic deployment, but it is not feasible with BEA's wldeploy task. The workaround is to do it programmatically through the JMX API:
<!-- Sets the load order on a Weblogic deployment -->
<scriptdef name="wlSetLoadOrder" language="groovy" classpath="${weblogic.home}/server/lib/weblogic.jar">
<!-- The name of the deployment -->
<attribute name="name" />
<!-- The load order -->
<attribute name="loadOrder" />
<!-- The admin URL of the domain -->
<attribute name="adminUrl" />
<!-- A weblogic user with administration rights -->
<attribute name="user" />
<!-- The user's password -->
<attribute name="password" />
<![CDATA[
import java.util.Hashtable
import javax.naming.Context
import javax.naming.InitialContext
import weblogic.management.MBeanHome
import weblogic.management.deploy.DeployerRuntime
import weblogic.management.deploy.DeploymentData
import org.apache.tools.ant.BuildException

try {
int loadOrder = Integer.parseInt(attributes["loadorder"])
self.log("Configuring load order " + loadOrder + " for " + attributes["name"])

// Connect to the MBean server
def ctx = new InitialContext(new Hashtable(
(Context.PROVIDER_URL) : attributes["adminurl"],
(Context.INITIAL_CONTEXT_FACTORY) : "weblogic.jndi.WLInitialContextFactory",
(Context.SECURITY_PRINCIPAL) : attributes["user"],
(Context.SECURITY_CREDENTIALS) : attributes["password"]))
def adminHome = ctx.lookup(MBeanHome.ADMIN_JNDI_NAME)

// Lookup the deployment's ApplicationMBean
def appMBean = adminHome.getMBean(attributes["name"], "Application")

// Set the JMX attribute
appMBean.setLoadOrder(loadOrder)
} catch (NumberFormatException e) {
throw new BuildException("Invalid value for loadOrder: " + attributes["loadorder"])
}
]]>
</scriptdef>
This new task is unsurprisingly invoked like any regular Ant task:
<wlSetLoadOrder name="myKillerApp" loadorder="200"
adminurl="t3://localhost:7001" user="admin" password="weblogic"
/>
Notes:
  • this works for Weblogic 8.1. I have not tried with later versions, but it can probably be easily adapted.
  • you will need to put the appropriate dependencies in Ant's classpath, namely: Groovy, Commons Logging and BSH. See this page.

1 comments:

123 123 said...
This comment has been removed by a blog administrator.