Using Maven’s maven-antrun-plugin like an Ant “exec” task

by Sherif

So I’ve been working on a project to migrate my old Ant build script into a Maven one. Whilst there is a lot of good Ant-to-Maven documentation out there, I had a few issues migrating a few simple Ant tasks I had. One of the things was I was trying to figure out how to replicate in Maven was the Apache Ant “exec” task.

In my Ant build file, I was making some “exec” calls in some tasks to execute a file via the command line. I wanted to do this to install and un-install my software, as part of the build process. I wanted to do the same thing in Maven.

So, here is the problem:

Snippet of my old Ant build.xml, which I want to ‘mavenise’ (if thats a word):

...
	<target name="unininstall">
	  <exec dir="${install.dir}" executable="cmd">
	  	<arg value="/c"/>	  	
	    <arg value="UninstallMyProgram-NT.bat"/>
	  </exec>
	</target>
	<target name="install" depends="unininstall">
	  <exec dir="${install.dir}" executable="cmd">
	  	<arg value="/c"/>
	    <arg value="InstallMyProgram-NT.bat"/>
	  </exec>
	</target>	

In the example above, I have two tasks. One to install ‘MyProgram’, and the other to uninstall it. If you are aware of the JavaServiceWrapper, you might have guessed that I’m actually trying to install my java program as a Windows service.

After doing a bit of research, it appears Maven does not have a direct equivalent. You can, however, use the Maven AntRun plugin to achieve the same affect. So in your Maven pom.xml, you will need the following:

     <plugin>
      <artifactId>maven-antrun-plugin </artifactId>
        <executions>
          <execution>
            <phase>install </phase>
            <configuration>
              <tasks name="Install MyProgram Windows service">
                <!-- Uninstall the old one first (if there is one) -->
                <exec
                  dir="${basedir}"
                  executable="${basedir}/bin/UninstallMyProgram-NT.bat"
                  failonerror="true">
                  <arg line=""/>
                </exec>
                <exec
                  dir="${basedir}"
                  executable="${basedir}/bin/InstallMyProgram-NT.bat"
                  failonerror="true">
                  <arg line=""/>
                </exec>
             </tasks>
            </configuration>
            <goals>
              <goal>run </goal>
            </goals>
          </execution>
        </executions>
      </plugin>

There you have it. For more information on the Maven AntRun plugin – check out the Maven site.