Technologies used in this article :

  1. Apache Ant

  2. JDK 1.6

  3. IBM WebSphere Application Server 6.1

1. Create a Java Project and a Class with 'main' method

Create a java project ('AntExecutor') and a class ('AntExecutor') in eclipse to run a simple Ant script from java code.

Note:
To know how to create a java project in Eclipse IDE, go through the following tutorial "Java Hello World Example using Eclipse IDE".

Sample project structure is shown below

Sample project structure

 

2. Setup Java Build Path

Create a folder, named as "lib" directly under project directory "AntExecutor". Copy "ant.jar" and "xercesImpl.jar" files into that "lib" folder. Setup the build path as shown in the screenshot below

setup build path

 

3. Write Ant Script

Create an xml file, named as "build.xml" directly under project directory "AntExecutor" and copy the following content

File : build.xml
Note :
Highlighted lines 3-11, are mainly for setting different properties required to start / stop an application, deployed in the server.

'wsadmin.bat' / 'wsadmin.sh' is the 'wsadmin' scripting tool. In my case, '/instld_soft/ibm/SDP/runtimes/base_v61/profiles/webdm01' is the WebSphere Application Server profile path. So location of wsadmin tool is '/instld_soft/ibm/SDP/runtimes/base_v61/profiles/webdm01/bin/wsadmin.bat'.

'AdminControl' is an object that enables the manipulation of MBeans running in a WebSphere server process.
Highlighted lines 25 & 42 are required to identify the application manager MBean for the server where the application resides.

'AdminControl' invokes the 'startApplication' / 'stopApplication' operation on the MBean, providing the application name that you want to start / stop.

 

4. Write Code

Copy the following code to the class AntExecutor

File : AntExecutor.java
package com.srccodes.example;

import java.io.File;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

/**
 * @author srccodes.com
 * @version 1.0
 */
public class AntExecutor {
    /**
     * To execute the default target specified in the Ant build.xml file
     * 
     * @param buildXmlFileFullPath
     */
    public static boolean executeAntTask(String buildXmlFileFullPath) {
        return executeAntTask(buildXmlFileFullPath, null);
    }
    
    /**
     * To execute a target specified in the Ant build.xml file
     * 
     * @param buildXmlFileFullPath
     * @param target
     */
    public static boolean executeAntTask(String buildXmlFileFullPath, String target) {
        boolean success = false;
        DefaultLogger consoleLogger = getConsoleLogger();

        // Prepare Ant project
        Project project = new Project();
        File buildFile = new File(buildXmlFileFullPath);
        project.setUserProperty("ant.file", buildFile.getAbsolutePath());
        project.addBuildListener(consoleLogger);

        // Capture event for Ant script build start / stop / failure
        try {
            project.fireBuildStarted();
            project.init();
            ProjectHelper projectHelper = ProjectHelper.getProjectHelper();
            project.addReference("ant.projectHelper", projectHelper);
            projectHelper.parse(project, buildFile);
            
            // If no target specified then default target will be executed.
            String targetToExecute = (target != null && target.trim().length() > 0) ? target.trim() : project.getDefaultTarget();
            project.executeTarget(targetToExecute);
            project.fireBuildFinished(null);
            success = true;
        } catch (BuildException buildException) {
            project.fireBuildFinished(buildException);
            throw new RuntimeException("!!! Unable to restart the IEHS App !!!", buildException);
        }
        
        return success;
    }
    
    /**
     * Logger to log output generated while executing ant script in console
     * 
     * @return
     */
    private static DefaultLogger getConsoleLogger() {
        DefaultLogger consoleLogger = new DefaultLogger();
        consoleLogger.setErrorPrintStream(System.err);
        consoleLogger.setOutputPrintStream(System.out);
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
        
        return consoleLogger;
    }
    
    /**
     * Main method to test code
     * 
     * @param args
     */
	public static void main(String[] args) {
		// To start the application 
		executeAntTask("build.xml", "start_Application");
		
		// To stop the application
		// executeAntTask("build.xml", "stop_Application");
	}
}
Note :

To know more about the above java code, go through the following tutorial "Invoke and Execute Hello World Ant Script Programmatically using Java Code".

To start the application, pass "start_Application" as ANT target to the method executeAntTask and to stop, pass "stop_Application".

 

5. Final project structure

After doing all the changes, the overall project structure will look like this

overall project structure

 

6. Run Your Code

Right click on 'AntExecutor.java' and select from context menu 'Run As' --> 'Java Application'.

 

7. Console Output

'executeAntTask("build.xml", "start_Application")' code statement will execute the target 'start_Application' and start the application in the WAS server.

'executeAntTask("build.xml", "stop_Application")' code statement will execute the target 'stop_Application' and stop the application deployed in the WAS server.

Console
start_Application:
     [exec] WASX7209I: Connected to process "server1" on node abhijitgNode01 using SOAP connector;  The type of process is: UnManagedProcess


BUILD SUCCESSFUL
Total time: 11 seconds

-----------------------------

stop_Application:
     [exec] WASX7209I: Connected to process "server1" on node abhijitgNode01 using SOAP connector;  The type of process is: UnManagedProcess


BUILD SUCCESSFUL
Total time: 9 seconds

 

Download Source Code

SrcCodes : AntExecutor.zip

 

References