24
Wed, Apr
0 New Articles

TechTip: Ant Is Your Java Builder's Best Friend, Part II

General
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Ant is a simple, effective tool that can guide you toward a solid build infrastructure.

 

In last week's article, I introduced the problem of a convoluted build process and presented Apache's Ant as an effective solution to the simplification of the process. In this week's article, we'll look at a complete example, including everything from the source code to the build artifacts within the Eclipse integrated development environment. This article assumes that the reader has a basic understanding of Eclipse and its Java projects.

Set Up Ant

Because we're focusing on using Ant from within Eclipse, the good news is that Ant is prepackaged as part of Eclipse's base installation image (be sure you're using Eclipse 3.2 or newer). This means there are no additional steps; your environment is ready for Ant! However, if you would like additional information about configuring the Ant runtime for use outside of Eclipse, there is a wealth of information available at the official Ant Web site.

Develop Source Code

Before we create an example build script, we need to create something to build. To demonstrate this process, let's create a simple HelloWorld Java program (shown below in Figure 1) in an Eclipse Java project named HelloWorld.

 

052308Cropper1.PNG 

Figure 1: Here's a simple HelloWorld Java program.

The Build Script

Now that we've got our source code, we need to build its "distributable" form (e.g., a file named HelloWorld.jar). Herein lies the problem: How do we build our sample program in a simple, reliable, and repeatable fashion?  This is where Ant saves the day.

 

build.xml

 

The first step in building our project with Ant is to create a build.xml file. Though the file doesn't need to be named build.xml, it must contain the .xml file extension (i.e., all Ant build files are merely XML files). A good practice is to place this build file in your project's root-level directory; in our case, that's the HelloWorld top-level directory.

 

Build File Structure

 

An Ant build file contains one or more targets. A target is effectively a named executable entity exposed to the user (e.g., compile might be the name of a target). It's common for a build file to consist of several targets wherein each target accomplishes one logical step within the overall build process. Build targets can also depend on one or more targets. That is, if a target depends on other targets, those targets will be implicitly executed when the target is run.

 

Although there's no enforcement of what your targets should be, in nearly all instances it's beneficial that your Ant build script contain at least these common targets:

 

  • load: This target is responsible for loading the source code. Often, the source exists in a content management system, and most CMS providers offer Ant support (e.g., Ant provides CVS-related tasks out-of-the-box).
  • preprocess: This target performs any preprocessing that needs to be done prior to compiling the source code (e.g., you might automatically increment your product's build number here).
  • compile: This target compiles the source code, sending any generated class files to a classes artifacts directory.
  • package: This target packages the compiled object code into a distributable entity (or entities); for example, you might create YourProduct.jar or YourProduct.war.
  • javadoc: This target produces documentation for your application's source code.
  • build: This target typically performs the entire build process, by either being dependent on all targets or simply being on the final target in a large dependency chain (e.g., imagine that A depends on B, which depends on C, etc. All would be performed via transitivity).
  • clean: This target deletes any artifacts produced by the Ant build; often, this is a dependent target by other targets, ensuring that the build always starts afresh.

 

Of course this list is by no means comprehensive; most product builds entail a lot of steps, but even the most complicated build processes can be split into many smaller entities (i.e., targets). This set of tasks is intended as a means of pointing you in the right direction. In doing so, one isn't forced to perform the entire build, but rather only a subset.

 

An Example

 

Let's look at an example Ant build file (below) that will build our HelloWorld program (Figure 1).

 

<!-- An example Ant build script that will automatically create HelloWorld.jar for us. -->

<project name="HelloWorld" default="build">

       <!-- Here we are defining a directory in which our build-related files will be placed,

       relative to the special Ant property, basedir, which refers to the directory from which

       Ant was launched. -->

       <property name="build.dir" location="${basedir}/build" />

       <!-- Defines the directory in which the source code will be placed. -->

       <property name="src.dir" location="${build.dir}/src" />

       <!-- Defines the directory in which the output (i.e., artifacts) of the build. -->

       <property name="artifacts.dir" location="${build.dir}/artifacts" />

       <!-- Defines the directory in which compiled code will be placed. -->

       <property name="classes.dir" location="${artifacts.dir}/classes" />

       <!-- Defines the directory in which distributable jars will be placed. -->

       <property name="jars.dir" location="${artifacts.dir}/jars" />

       <!-- The clean target is responsible for deleting old build artifacts and preparing for

       a fresh build to occur. -->

       <target name="clean">

              <delete dir="${build.dir}" />

              <mkdir dir="${build.dir}" />

              <mkdir dir="${src.dir}" />

              <mkdir dir="${artifacts.dir}" />

              <mkdir dir="${classes.dir}" />

              <mkdir dir="${jars.dir}" />

       </target>

       <!-- Defines the build target, which is dependent upon the jar target completing. -->

       <target name="build" depends="package" />

       <!-- Load our source code from our base directory. In most instances, you'd likely

       retrieve your source code from your source control management system. -->

       <target name="load" depends="clean">

              <copy todir="${src.dir}" preservelastmodified="true">

                     <fileset dir="${basedir}">

                           <include name="**/*.java" />

                     </fileset>

              </copy>

       </target>

       <!-- Perform any necessary pre-processing on the source code. In this case, we're

       not going to do anything, but you might imagine incrementing a build revision, etc. -->

       <target name="preprocess" depends="load" />

       <!-- Compile our source code, directing generated .class files to the classes directory. -->

       <target name="compile" depends="preprocess">

              <javac srcdir="${src.dir}" destdir="${classes.dir}" />

       </target>

       <!-- Create our .jar file, which consists of all compiled .class files. -->

       <target name="package" depends="compile">

              <jar destfile="${jars.dir}/HelloWorld.jar">

                     <fileset dir="${classes.dir}">

                           <include name="**/*.class" />

                     </fileset>

              </jar>

       </target>

</project>

Running the Build Script

Eclipse provides out-of-the-box support for you to work with your Ant build files. To load the Ant view, click on Window > Show View > Other > Ant > Ant. You can then drag and drop any of your Ant build files into the Ant view (Figure 2). Once loaded, further expanding a particular Ant build will display its executable targets. Double-clicking a target will cause it to execute. This simplicity becomes especially beneficial when you need to perform several builds within a short period of time (e.g., during development).

 

052308Cropper2.PNG

Figure 2: This is the Ant view within Eclipse.

Using the Build Artifacts

Now that our build has successfully completed, we can navigate to the appropriate artifact directory and grab the build artifacts of interest (e.g., HelloWorld.jar, auto-generated Java documentation, etc.). These artifacts may then be distributed as needed; you may even create your Ant script such that it not only builds your projects, but also uploads your build artifacts to some well-known location (i.e., a common hub for distribution).

Go Build!

By now, you should have not only a solid understanding of why it's important to have a solid build infrastructure, but also a simple and effective tool to guide you along the way (hint, hint: Apache Ant). While this article by no means scratches the surface of all that Ant has to offer, it does make you aware of the basics and offer you some helpful suggestions to dig a little deeper. So go on; try building your next project with Ant.

Joe Cropper is a Software Engineer at IBM in Rochester, Minnesota. He works as part of the Cloud Systems Software Development organization, focusing on virtualization and cloud management solutions. Joe has held a number of roles in other organizations as well, ranging from IBM i and Electronic Support. His areas of expertise include virtualization and cloud management, OpenStack, Java EE, and multi-tiered applications. Joe can be reached via email at This email address is being protected from spambots. You need JavaScript enabled to view it..

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: