Welcome!

Apache Authors: Anne Buff, Elizabeth White, Liz McMillan, Roger Strukhoff, Sanjeev Sharma

Related Topics: Apache, ColdFusion, PHP, Ruby, Perl, Python

Apache: Article

An Introduction to Ant

Automate and improve your build and deploy process

Writing shell scripts to automate the build and deploy process for ColdFusion applications is not very much fun. The Jakarta Ant project is an open-source, cross-platform alternative that makes it easy to automate the build and deploy process.

But My Build and Deploy Process is Fine....
Maybe your build and deploy process for your latest application is fine - you type a single command and your build process automatically retrieves your application from the source control system, configures the application appropriately for the target environment, and copies all the necessary files to the production servers while you head to the coffee shop for your morning cup of caffeine and the newspaper. But I know that the reality for the vast majority of projects I've seen (including many of my own applications!) are built and deployed using a written multistep checklist - some steps automated by simple shell scripts and some done by hand. With time a scarce commodity on most projects, it's not a surprise that anything other than the ColdFusion application itself gets little, if any, attention.

But how many times have you personally been burned by a bad build or deploy? Maybe forgetting to copy a custom tag to the \CFusionMX\CustomTags directory? Or deploying the wrong version of a ColdFusion template? Maybe you forgot to toggle the data source name from the development server to the production server? Or neglected to disable some debugging code? The list goes on. How much time did you waste finding and fixing the problem? Odds are it was a lot, and that the problem happened at the least opportune time, like during a major production release! If there was a simple, free, cross-platform, extensible tool that would let you write automated build and deploy scripts, wouldn't it make sense to use it?

There are some traditional tools for automating builds: the venerable make is familiar to anyone who's done much work on Linux or with C applications; jam may be familiar to some hard-core open-source developers; and native shells on Windows (DOS and third-party replacements including cygwin) and Unix (bash, csh, zsh, and their relatives) can all be used. But anyone who has used make or its derivatives can relate to the frustrations of accidentally putting a space in front of a tab and trying to figure out why the script is not working. And shell scripts are both platform specific and can be very limited in their capabilities (particularly the DOS shell).

One Java programmer, James Duncan Davidson, became so frustrated with the existing build tools while he was creating Tomcat (the official reference implementation for Java Servlets and JavaServer Pages) that he wrote his own build tool, which he dubbed Another Neat Tool (Ant). The Ant tool itself is implemented in Java, which allows it to run consistently across most modern operating systems, and also makes it easy to extend so that it can do any tasks that Java can (more on that later). Ant-built scripts are written in XML, which makes them much easier to write (and validate!). Ant rapidly expanded into a number of Apache Jakarta projects and from there to the many Java developers who downloaded the Jakarta tools. Today, Ant is a de facto standard tool for automating many aspects of the Java software development process. Instead of the "make install" of the C world, Java developers now have "ant deploy"!

So why should you, as a ColdFusion developer, be interested in Ant? If your ColdFusion applications deploy seamlessly to Linux and Windows servers with a single command, then you might not need Ant, but otherwise it's going to become a key tool in your software development toolbox. More important, now that ColdFusion MX is so tightly coupled to the Java world, using Java tools simply makes sense. Even the ColdFusion MX updaters use Ant scripts for part of the upgrade process!

Installing Ant
The Apache Ant project home page http://ant.apache.org/ provides both source and binary distributions of Ant, as well as the manual, links to key resources, and even a Wiki. For most purposes, the binary distribution for your platform should be sufficient, especially if you're new to Ant. The latest Ant release, 1.6.0, debuted in mid-December of 2003, though there's nothing wrong with Ant 1.5.x should that version already be available in your environment. And since Ant is a Java application, you'll also need an installed JDK, version 1.2 or later - the latest Sun JDK 1.4 is available from http://java.sun.com/j2se/1.4.2/download.html.

Installing the Ant binaries is simply a matter of unzipping the archive into a directory on your computer and completing two configuration steps:

  1. The Ant\bin directory needs to be added to your path.
  2. Add the environment variable ANT_HOME, and have it point to the installation directory.

    There is also an additional, optional, step:

  3. Add the environment variable JAVA_HOME, which points to the installed JDK directory.

So on a Windows 2000/XP computer, the configuration might look like Listing 1. There are bash and csh equivalents for Unix in the Ant reference manual (http://ant.apache.org/manual/index.html).

You can test your installation by opening a console window and typing

ant -version

which should produce a version number and compile date for your Ant installation.

Using Ant
Now that you've got Ant installed, what's the next step? Why, a build file of course! You're going to need a console window and your favorite text (or XML) editor to get started. The Ant command expects a buildfile (which defaults to build.xml) that contains an XML description of build targets, which are steps in the build process. And each target consists of one or more tasks that need to occur. Listing 2 contains a very simple buildfile. If you save Listing 2 as build.xml and simply type "ant", you'll get something that looks like this:

Buildfile: build.xml
help:
[echo] usage: ant [target]
[echo] typical targets: init, dist, deploy, help
BUILD SUCCESSFUL
Total time: 4 seconds

It's worth noting that since we didn't pass in any particular target, Ant used the default target name defined in the <project> tag. Typing "ant help" will produce the same output. In this buildfile, we've got a single <target> that has two <echo> tasks. The <echo> task simply writes text to the screen.

Now that we've got the Ant equivalent of a "Hello World" application, let's get down to the business of creating the build process for a real ColdFusion application using Ant. To get started all we need to do is retrieve the source code from the source code control repository (I'm going to use Microsoft Visual SourceSafe for this example) and prepare it for deployment. I'm going to use the following Ant targets for our build process:

  1. init: Create the directories for the project
  2. getSource: Pull the latest source code from the repository
  3. build: Process the source code to prepare it for the deployment environment
  4. dist: Package the source for distribution/deployment
  5. deploy: Copy the distribution package to the production server
  6. clean: Remove all files and directories associated with the project

The entire buildfile is shown in Listing 3, and it's certainly expanded a lot!

Putting Our Buildfile Under the Magnifying Glass
There are a lot of new things to absorb in this buildfile and we have limited space, so we're going to look at each target individually in the following section and go over the major points. If you want details on any of the specific tasks (or any of the dozens of other Ant tasks) you might want to peruse the Ant online manual (http://ant.apache.org/manual/index.html) as you read along.

The init target shouldn't be too hard to interpret - it uses the <mkdir> task to create three directories: src, build, and dist. This task will create each of these three directories if they don't already exist. As an aside, these specific directory names have become conventional on Ant projects. Type "ant init" and the three directories will be created to hold your application. Since the <mkdir> in our buildfile is using relative paths, the directories will be created underneath the directory where the buildfile is located.

The clean target looks very similar to the init target, with the <delete> task replacing the <mkdir>. As you probably intuited, we're simply deleting the directories we created with the init. But one new feature is the depends attribute in the <target> tag. The depends attribute can be used to describe dependencies between targets. In this case, the buildfile is indicating that the clean target can run only after the init target has been run, so Ant automatically runs init for you, but only if the target needs to be run! You can test this by running the clean target two or more times - if the directories exist (and thus the init dependency is satisfied), the clean tasks simply deletes them, but if the directories do not exist, Ant runs the dependent init target to create them and then deletes them. Try it and watch the output!

The getsource target is where things really get interesting. We want to get the source code out of our Microsoft Visual SourceSafe (VSS) repository so we can build and deploy it. Ant has built-in tasks for manipulating all of the major (and many minor) source control applications. (As an aside, there are actually eight Ant tasks for manipulating VSS; these and all of the other vendor-specific tasks are listed in the "Optional Tasks" section of the Ant manual.) In this example, we're using <vssget> to pull code from the VSS. The buildfile is passing in a number of VSS-specific parameters which result in the latest source code being pulled from the repository and put into the \src directory. Note that this target also depends on the init target, since the \src directory needs to exist before we start getting the source code.

The build target is pretty simple in this buildfile - it uses the <copy> task to copy all of the files in the \src directory to the \build directory. The <copy> task is interesting because it uses an Ant type, the <fileset>. There are over a dozen Ant types, which represent complex data structures that Ant natively understands. In this case we're defining a set of files with the <fileset> type, which is then used by the <copy> task.

The build target depends on the getsource task, since we need source code before we can copy it to another directory, since getsource depends on init, we've now used the depends attribute to chain three targets together in the proper order, which you can verify by running the build target and watching the dependent tasks execute in the Ant output.

The dist target is exactly like the build target, simply copying files from one directory to another. If we were using Ant for a Java application, this is the step where the compiled class files would be packaged into a JAR file for distribution. So the net result of all of these steps so far is to pull out the source code from VSS, copy it to the \build directory, and then copy it to the \dist directory. We could have skipped the build and dist targets, but we'll talk more about why they're useful in the final section of this article.

Finally, we've got the deploy target, which in this case is copying the files in the \dist directory to another directory, perhaps a network share to the integration or production server. We're using the <mkdir> and <copy> tasks again, but this time the directory name looks a little weird. One powerful concept in Ant is the "property". In this example, the deploy target expects a property called "deploy.dir", which represents the directory the \dist directory should be deployed to. The syntax for a property is ${varname}. Properties can be configured a number of ways using the <property> task, ranging from assigning it directly in the buildfile to using environment variables or the command line. Let's assume for a minute that I can deploy the files to two directories, c:\apache2\htdocs\test for my local test Web server, and l:\apache2\htdocs\production for the production Web server. The property can be input from the command line using the -Dproperty=value syntax, like the following example

ant deploy -Ddeploy.dir=c:\\apache2\\htdocs\\test

Note that there is no space between the -D option and the property=value information. And since I'm running on a Windows machine, I do have to remember to escape the backslash just like I would have to in a Java .properties file. But the buildfile doesn't know anything about Windows, Linux, Mac, or anything else, so you can deploy to /var/httpd/htdocs/test just as easily.

Next Steps
The first step I'd recommend taking is to automate your build process using Ant if you don't already have a solution. Now. Right now. Go! And if you do have a build process in place, I'd suggest taking a hard look at whether it's worth moving to Ant for its simplicity (relatively speaking), extensibility, and cross-platform support. We've literally just scratched the surface of Ant, but this buildfile is already useful and a great starting point for experimentation (and maybe another article? Let me know!). Just some quick tidbits to whet your appetite for more Ant:

  • Use <filter>s to replace tokens in files with new values, maybe to toggle debugging flags and set datasource names that vary between deployment environments.
  • Schedule Ant using cron, at, Windows scheduler, or the like for nightly builds, and send e-mail to the team about the results.
  • Integrate automated testing tools (JUnit, HTTPUnit, etc) into the build.
  • Deploy using FTP, telnet, or other methods to a remote server.
  • Write your own Ant tasks that extend existing tasks or implement new functionality in Java (check out http://sourceforge.net/projects/ant-contrib first to see if someone already beat you to it).

If you're looking for more on Ant, the Ant manual is a great resource, but I'd also heartily recommend the book, Java Development with Ant, by Erik Hatcher and Steve Loughran, especially if you're working with Java as well as ColdFusion (and in the interest of full disclosure, I should mention Erik was my officemate for nearly a year while he wrote the book). I hate to admit it, but since I started using Ant, I find creating a build process for new applications (gulp!) fun. Okay, maybe not fun, but at least much less frustrating than DOS scripts, make, and the manual lists I used to use. In fact, right now I'm headed off to have a cup of coffee since I just kicked off my release build... "ant deploy". Phew! Tough day. Probably enough time for a venti today...

More Stories By John Ashenfelter

John Paul Ashenfelter is CTO and founder of TransitionPoint.com, a consulting firm based in central Virginia that specializes in developing and re-architecting ColdFusion Web applications for small- and mid-sized businesses. John Paul has been using ColdFusion since 1998 and is the author of three ColdFusion books as well as the upcoming Data Warehousing with MySQL.

Comments (2)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today that Harbinger Systems will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Harbinger Systems is a global company providing software technology services. Since 1990, Harbinger has developed a strong customer base worldwide. Its customers include software product companies ranging from hi-tech start-ups in Silicon Valley to leading product companies in the US and large in-house IT organizations.
The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
SYS-CON Events announces a new pavilion on the Cloud Expo floor where WebRTC converges with the Internet of Things. Pavilion will showcase WebRTC and the Internet of Things. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices--computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
As a disruptive technology, Web Real-Time Communication (WebRTC), which is an emerging standard of web communications, is redefining how brands and consumers communicate in real time. The on-going narrative around WebRTC has largely been around incorporating video, audio and chat functions to apps. In his session at Internet of @ThingsExpo, Alex Gouaillard, Founder and CTO of Temasys Communications, will look at a fourth element – data channels – and talk about its potential to move WebRTC beyond browsers and into the Internet of Things.
SYS-CON Events announced today that Gigaom Research has been named "Media Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Ashar Baig, Research Director, Cloud, at Gigaom Research, will also lead a Power Panel on the topic "Choosing the Right Cloud Option." Gigaom Research provides timely, in-depth analysis of emerging technologies for individual and corporate subscribers. Gigaom Research's network of 200+ independent analysts provides new content daily that bridges the gap between break...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.