Stopping Tomcat with Ant

Problem

You want to stop Tomcat using Ant.

Solution

Create a target that invokes the custom Ant task com.oreilly.javaxp.tomcat.tasks.StopTomcatTask.

Discussion

Typically, a server is stopped from a command prompt using a predefined script distributed with the server. Since we have a new task to start Tomcat, it only seems fitting to provide a way to stop Tomcat, too. The ability to stop Tomcat is very useful from within an Ant buildfile, especially if we need to ensure that Tomcat is stopped before allowing any other Ant targets to execute. Example 10-8 shows the StopTomcatTask class. This new task extends AbstractTomcatTask, which we saw in Recipe 10.6, and causes Tomcat to shutdown. The task patiently waits until Tomcat is stopped before relinquishing control to other tasks.

An alternative approach is executing Tomcat’s shutdown script with Ant’s exec task. This approach works fine if you do not care if and when Tomcat actually stops. The same holds true for starting Tomcat.

Example 10-8. StopTomcatTask class

package com.oreilly.javaxp.tomcat.tasks;

public class StopTomcatTask extends AbstractTomcatTask {
    
    public String getScriptToExecute(  ) {
        return "shutdown";
    }

    public boolean isStarting(  ) {
        return false;
    }
}

Example 10-9 shows how to use this task in an Ant buildfile.

Example 10-9. Stopping Tomcat with Ant

<target name="stop.tomcat"> <taskdef name="stoptomcat" classname="com.oreilly.javaxp.tomcat.tasks.StopTomcatTask"> <classpath> <path location="${dir.build}"/> ...

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.