Interview Questions

ANT Build Execution from Java

Build Engineers are usually faced with requirements to notify the development team whenever a build is successfully completed or if there is an exception in build. ANT framework provides a simple API to do this. Have a look at the following code.

AntBuild.java

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */


import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;

import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.BuildLogger;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

public class AntBuild
{
        public static void main(String[] args)
        {
                try
                {
                        String fileName = null;
                        if (args.length > 0)
                        {
                                fileName = args[0];
                        }
                        else
                        {
                                fileName = "C:\\buildCommon.xml";
                        }
                       
                        File buildFile = new File(fileName);
                        Project p = new Project();
                        p.setUserProperty("ant.file", buildFile.getAbsolutePath());

                        AntBuildMailLogger antBuildMailLogger = new AntBuildMailLogger();
                        antBuildMailLogger.setMessageOutputLevel(Project.MSG_INFO);

                        p.addBuildListener(antBuildMailLogger);

                        try
                        {
                                p.fireBuildStarted();
                                p.init();
                                ProjectHelper helper = ProjectHelper.getProjectHelper();
                                p.addReference("ant.projectHelper", helper);
                                helper.parse(p, buildFile);
                                p.executeTarget("createWar");
                                p.fireBuildFinished(null);
                        }
                        catch (BuildException e)
                        {
                                p.fireBuildFinished(e);
                        }
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                        System.out.println("Exception Occured -> " + e.getMessage());
                }
        }
}

class AntBuildMailLogger implements BuildLogger
{
        String  pHost           = "smtp.techdive.com";  // provide the smtp host below
        String  pTo                     = "admin@techdive.com"; // to send email to multiple users, provide email ids as comma separated values
        String  pFrom           = "admin@techdive.com";
        String  pSubject        = "";

        private void sendEmail(String subject, String pBody)
        {
                Mailer eMail = new Mailer(pHost);
                eMail.setTo(pTo);
                eMail.setFrom(pFrom);
                eMail.setSubject(subject);
                eMail.setBody(pBody);
                eMail.sendMail();
        }

        public void buildFinished(BuildEvent arg0)
        {
                if (arg0.getException() == null)
                        sendEmail("Build Successful", "Build Finished successfully on " + new Date().toString());
                else
                        sendEmail("Exception in Build",
                                        "Exception in Build on " + new Date().toString() + "\n\n" + arg0.getException());
        }

        public void buildStarted(BuildEvent arg0)
        {
        }

        public void messageLogged(BuildEvent arg0)
        {
        }

        public void targetFinished(BuildEvent arg0)
        {
        }

        public void targetStarted(BuildEvent arg0)
        {
        }

        public void taskFinished(BuildEvent arg0)
        {
        }

        public void taskStarted(BuildEvent arg0)
        {
        }

        public void setEmacsMode(boolean arg0)
        {
        }

        public void setErrorPrintStream(PrintStream arg0)
        {
        }

        public void setMessageOutputLevel(int arg0)
        {
        }

        public void setOutputPrintStream(PrintStream arg0)
        {
        }
}

The AntBuild class uses the Project and ProjectHelper classes available in the ANT API to execute a build.xml file. It also adds a build listener to the Project Class. This class should implement BuildListener interface, so that it gets notified about the build events like start, finish and exception. Here we have added a build listener which notifies users through email. So, whenever a build fails a list of users will be notified through email. This class ANT Build can be scheduled to run under a cronjob, so that it runs the build in the specified time and notifies users.

To know about the Mailer.java class used in the above class , go through the article
Send Email using Java.