Apache Ant 101: Make the Java project to make fun

zhaozj2021-02-16  94

Apache Ant 101: Make the Java project to make fun

The content described in this tutorial

In this tutorial, you will learn Ant this Java TM project build tool. Due to its flexibility and ease of use, Ant quickly spreads in Java developers, so you need to know more about it.

You don't have to have previous Ant experience or knowledge before continuing to learn this tutorial. We will first look at the basic structure of the ANT Generation File (Building, and learn how to call this tool. We will gradually complete the steps to generate files for a simple Java project, and then examine some other useful features of Ant, including file system operation and pattern matching. Finally, write an extension Ant function to end this tutorial.

In the process of learning this tutorial, we will show how to run Ant from the command line and from other open source Eclipse IDEs. Examples in this tutorial don't need these two environments; you can choose one or even choose a different development environment, as long as the environment supports Ant. If you choose to use Ant from the command line, and Ant has not been installed on the machine, you need to follow the installation instructions on the ANT home page (see Resources to get related links). Instead, if you decide to use only the Eclipse environment, you don't need to install Ant alone because Eclipse has included it. If you haven't had Eclipse, you can download Eclipse.org (see Resources).

getting Started

Who should learn this tutorial?

If you are writing Java code but have not used Ant, then this tutorial is to prepare for you. Whether you currently use a different build tool, or if you don't use the build tool at all, you can use more knowledge about Ant, which may prompt you to use it.

If you are already using Ant, you may still find some interesting things in this tutorial. Maybe you will find some anticnections that are expected or unable to fully understand; this tutorial will help you. Or maybe you are familiar with the foundation of Ant, but you still want to know advanced topics such as those who will generate file links, use CVS knowledge bases or write custom tasks; this tutorial will introduce all of these topics.

Ant is mainly designed to generate Java projects, but this is not its only use. Many people find it very helpful to other tasks. For example, perform file system operation in a cross-platform manner. In addition, there are many available third-party Ant tasks, and the written custom Ant tasks are relatively simple, so it is easy to customize ANT for specific applications.

About author

Matt Chapman 1996 is a consulting software engineer for IBM Center for Java Technology in the UK. He has been committed to Java technology in the past seven years, including Java virtual machine implementation and various platforms, user interface toolkits Swing and AWT, and tools recently written for Eclipse platforms. Matt has a degree in computer science, and is still a Sun certified Java programmer. Can contact him through mchapman@uk.ibm.com.

ANT foundation

Introduction

This section will outline the functionality and advantages of Ant, and discuss its historical profile and increasing popularity. Then we directly enter the discussion of the ANT foundation by examining the basic structure of the most basic generated file. We will also introduce the concept of attributes and dependencies.

What is ANT?

Apache Ant is a Java-based generating tool. According to the initial founder James Duncan Davidson, the name of this tool is the first letter of Another Neat Tool (another neat tool). The generation tool is used in software development to convert the source code and other input files to the executable form (also possible to convert to an installed product image form). As the application's generation process is more complex, ensure that exact the same generating steps are used during each generation, while achieving as many automation as possible to generate a consistent generation version, which is more important. Traditional projects in C or C often use the Make tool to do this, where the generated task is to be executed by calling the shell command, and the dependency defines between each generated file so that they always execute with the necessary order .

Ant is similar to Make, which also defines the dependencies between generated files; however, is different from the use of platform-specific shell commands, which uses a cross-platform Java class. Using Ant, you can write a single generated file, this generating file is consistent on any Java platform (because Ant itself is also implemented using Java language); this is the biggest advantage of Ant.

Other key advantages of Ant include its outstanding simplicity and seamless use of custom features to extend its capabilities. I hope that after completing the rest of this tutorial, you will enjoy these advantages of Ant.

Ant brief history

ANT was originally a internal component of Tomcat, Tomcat is a servlet container used in the Java Servlet and JavaServer Pages (JSP). The Tomcat code base was donated to the Apache Software Foundation; where it became an integral part of the Apache Jakarta project, the project was committed to generating a server-side solution for open source for the Java platform. The usefulness of Ant has been approved and used in other Jakarta subprojects. Thus, it also became a Jakarta sub-project, the first independent version was released in July 2000.

Since then, the popularity of Ant has been constantly increasing. It won countless industry awards and became the fact that the actual standard for generating an open source Java project. In November 2002, these success have been confirmed, and Ant is upgraded to the top Apache project.

On the occasion of writing this article, the current stability version of Ant is

1.5.4

It supports all JDK versions after 1.1. The next version (ie version 1.6 version) is already available, these versions require JDK 1.2 or higher. The future version 2.0 is also planned, which will involve a major architecture redesign. Ant 2.0 will be characterized by improved consistency and enhancements, while still maintaining the simplicity of Ant, easy to understand, and scalability.

ANT generation file analysis

Ant does not define its own custom syntax; in contrast, its generated file is written in XML (see Resources). There is a set of Ant's predefined XML elements, and as you will see in the next section, you can define new elements to extend the functionality of Ant. Each generated file consists of a single Project element that includes one or more Target elements. One goal is a step that is defined during the generation process, which performs any number of operations, such as compiling a set of source files. These operations themselves are executed by other dedicated task tags, we will see this later. These tasks are then packet into each Target element as needed. All operations necessary for a generation process can be placed in a single target element, but flexibility is reduced. Divide those operations into logical generating steps, each step in its own Target element, which is usually more desirable. This can perform a separate portion of the overall generation process, but do not necessarily perform other parts. For example, by calling only some targets, you can compile the source code of the project, but you don't have to create an installable project image. Top Project elements need to include a default property, if there is no target when Ant is called, this property will specify the target to be executed. Then you need to use a Target element to define the target itself. Below is the most basic generated file:

Run Ant

Introduction

Apache Ant can be called in a variety of different ways. In terms of itself, Ant is a tool of command line, usually from UNIX or Linux Shell prompt or Windows command prompt, generating files, using your own text editor to write. If the item to be generated is developed in this way, then call Ant is very good, but many people find Ide more convenient. Most IDEs provide some level of support for Ant, so at least in the case of using IDE, you don't have to trouble away from IDE to perform command line operations to call ANT generation tasks.

In this section, we will examine how to use Ant from the command line and learn some useful command line options. Then briefly understand the ANT support provided by the Eclipse platform of the open source code. (In order to make the most of the following section, you should be very passively familiar with Eclipse.)

Run Ant from the command line

The ANT from the command prompt can be simply simply typed separate ANT. If you do this, Ant will use the default generated file; the default target specified in the generated file is the target to be generated. You can also specify a number of command line options, followed by any number of generated destination, and Ant will generate each target in order and resolve all dependencies during this process.

Below is some typical outputs of the ANT generation task executed from the command line:

Buildfile: build.xml

INIT:

[MKDIR] CREATED DIR: E: / TUTORIALS / ANT / EXAMPLE / BUILD

[mkdir] create Dir: E: / TUTORIALS / ANT / EXAMPLE / DIST

Compile:

[Javac] Compiling 8 Source Files To E: / Tutorials / Ant / Example / Build

Dist:

[jar] building jar: E: /Tutorials/ant/example/dist/example.jar

Build Successful

Total Time: 2 Seconds

As we continue to learn about this tutorial, we will understand what all these outputs mean.

Command line option

Just like the Make tool to find a generated file named makefile by default, Ant looks for a file called Build.xml. Therefore, if your generated file uses this name, you do not need to specify it on the command line. Of course, sometimes it is more convenient to use the generated file with other names. In such cases, you need to use the -buildfile parameter (-f is its shortclock). Another useful option is -d, which is used to set the properties that can then be used in the generated file. This is very useful for configuring the generation process you want to start in some way. For example, in order to set the NAME property to a particular value, you will use an option similar to the following:

-Dmetal = Beryllium

This feature can be used to override the initial attribute settings in the generated file. As mentioned earlier, the value of the attribute cannot be changed. The -d flag sets an attribute before reading any information in the generated file; since the fingerfaction is fed off in this initial assignment, it does not change its value.

IDE integration

Due to the popularity of Ant, most modern IDEs are now integrated with its support, and many other IDEs provide support to it in the plugin. Supported environmental lists include Jedit and Jext Editor, Borland JBuilder, Intellij Idea, Java Development Environment For Emacs (JDEE), NetBeans IDE, Eclipse, and WebSphere? Studio Application Developer.

See Resources for more information on Ant's extensive IDE support. In the rest of this section, we will explore the ANT support included in the Eclipse environment of open source.

Eclipse support for Ant

The Eclipse project of open source code provides a lot of support to Ant. These supported cores are Eclipse's ANT editor, which is characterized by syntax highlighting. The editor is shown below:

This editor provides content assist - for example, type tag, and a brief description of this task.

You can also see an outline, which shows the structure of the generated file and provides a convenient way to navigate in this file. There is also an ANT view that allows you to generate a target based on many different ANT files.

Run an ANT generation task from Eclipse

Files named Build.xml use an Ant icon to identify and decorate in the Eclipse's navigation program view. (If your generated file has a different name, see the file association in Eclipse.) Right-click on these files to provide a Run Ant ... menu option, select this menu option to open a dialog that is similar as follows:

All goals from the generated file are displayed, and the default target is selected. After you decide whether you want to change the default target, press the RUN button to run Ant. Eclipse will switch to the Console view as shown below. Error will be displayed in different colors, you can click on the task name in the output to jump to the corresponding call point in the generated file.

Document association in Eclipse

By default, Eclipse uses an ANT editor only for files named Build.xml, but it can be easily configured to identify files with other names. Select Window => Preferences from the menu, then expand the Workbench group, select the File Associations parameter setting page. Then add a new file type to the expected file name. For example, you can add a new file type for all files named myBuild.xml. If you want to have all the files with the .XML suffix (except for the special file name, such as Plugin.xml, it is available in Eclipse to overwrite the wildcard designation), you can even use * .xml. Finally, add an associated editor to this new file type, then select Ant Editor from the editor list, as shown below: Generate a simple Java project

Introduction

Now we have clearly the format of Ant generation files and understand how to define attributes and dependencies and how to run Ant, and you can start building a generated environment for a basic Java project. This will include learning Ant tasks for compiling source code and combined JAR files.

Compile source code

Since Ant's main goal is to generate Java applications, it can be inherently, excellent support to call Javac compilers and other Java-related tasks. Below is a writing method for compiling the task of Java code:

This label is looking for all files in the SRC directory to extension, and call the Javac compiler to generate class files in the same directory. Of course, placing class files in a separate directory structure will usually be clearer; you can make Ant to this point by adding a Destdir property. Other useful properties include:

ClassPath: Equivalent to the -classpath option for Javac.

Debug = "true": Indicates the compiler to compile the source file with the debug information.

An important feature of the Javac mission is that it only compiles the source files it thinks need to be compiled. If a class file already exists, the corresponding source file has not changed since the class file generation, the source file will not be recompiled. The output of the JavaC task shows the number of source files actually compiled. Write a Clean target to remove any class file generated from the target directory is a good habit. You can use this task if you want to make sure all source files are compiled. This behavior portrayed the characteristics of many tasks of Ant: If a task can determine that the requested operation does not need to be executed, then this action will be skipped.

Like Ant, the Javac compiler itself is also implemented in Java language. This is very advantageous for use of Javac tasks in Ant because it typically calls the compiler class in the same Java virtual machine (JVM) in the ANT run. When you need to compile Java code each time, other build tools typically need to run a new Javac process, requiring a new JVM instance. But in the case of using ANT, only a single JVM instance is required, which is used to run the ANT itself, also for performing all necessary compilation tasks (and other related tasks, such as processing JAR files). This is a much efficient resource usage, which greatly shortens the project generation time.

Compiler option

As we see from the previous section, the default behavior of Ant's Javac mission is to call any JVM standard compiler running Ant itself. However, sometimes you may want to call the compiler separately - For example, when you want to specify certain memory options for the compiler, or when you need to use a different level compiler. To achieve this, simply set the JAVAC's fork property to true, such as the following:

If you want to specify a different Javac executable and pass a maximum memory setting to it, you can do this below:

MemoryMaxImumsize = "

128M

"/>

You can even configure Ant to use a different compiler. The supported compiler includes an open source JIKES compiler and a GCI compiler from the GNU Compiler Set (GNU Compiler Collection, GCC). (See Resources for more information on these two compilers.) You can specify these compilers in two ways: You can set the build.Compiler property, which will be applied to all occasions using the Javac task; or as needed Set the Compiler property in each Javac task.

The Javac task also supports many other options. Please refer to the ANT manual for more details (see Resources).

Create a JAR file

After compiling the Java source file, the result class file is usually packaged into a JAR file, this file is similar to the ZIP archive. Each JAR file contains a manifest file that specifies the properties of the JAR file.

Below is a simple usage example of the JAR task in Ant:

This will create a JAR file called Package.jar and add all files in the classs directory (JAR files can contain any type of file, not just class files). There is no specified manifest file here, so Ant will provide a basic manifest file.

The Manifest property allows you to specify a file that is used as the JAR file. The content of the list file can also be specified in the generated file using the Manifest task. This task can be written to a manifest file like a file system, or can actually nested within JAR in order to create a manifest file and JAR file at once. E.g:

Timestamp generation

Use the current time and date in the generated environment to mark the output of a generated task in some way to record when it is generated, which is often desirable. This may involve editing a file to insert a string to specify the date and time, or merge this information into the file name of the JAR or ZIP file. This needs is solved by simple but very useful TSTAMP tasks. This task is usually called at the beginning of a certain generation process, such as in an init target. This task does not require attributes, and only is enough in many cases.

TSTAMP does not produce any output; in contrast, it sets the ANT attribute based on the current system time and date. Below is some properties of TSTAMP settings, an example of each attribute, and the values ​​of these attributes can be set:

Attributes

Description

example

DSTAMP

Set to the current date, the default format is YYYYMMDD

20031217

TSTAMP

Set to the current time, the default format is HHMM

1603

Today

Set to the current date, with complete month

2003

December

On the 17th

For example, in the previous section, we created a JAR file as follows:

After calling the TSTAMP task, we can name the JAR file based on the date, as shown below:

Therefore, if this task is called on December 17, 2003, the JAR file will be named package-20031217.jar.

You can also configure TSTAMP tasks to set different properties, apply a time offset before or after a current time, or format the string in different ways. All of this is done using a nested Format element, as shown below:

Pattern = "hh: mm: ss"

OFFSET = "10" unit = "minute" />

The above list sets the OFFSET_TIME attribute to the number of hours, minutes and seconds of the distance after 10 minutes.

The characters used to define the format string are the same as those defined by the Java.Text.SIMPLEDATEFORMAT class.

Integrate

As a few sections provide us with sufficient knowledge required to generate a simple Java project. Here, these code snippets will be combined into a complete generated file, which will compile all the source code in the src directory, put the result class file in the build directory, then package all class files into a JAR file in the dist directory . To test this generated file, what you need is the SRC directory containing one or more Java source code files - this directory can contain a large source file from a simple "Hell World" to a large source file from a existing project. Anything. If you need to add JAR files or anything else to Java ClassPath to successfully compile the source code, you only need to add a ClassPath property to it in the Javac task.

The generated file looks as follows:

a Simple Java Project

Below is an example output of a certain generation process executed using this file (you get the output may not be the same, depending on the content of the src directory):

Buildfile: build.xml

INIT:

[MKDIR] Created Dir: E: / Tutorial / Javaexample / Build

[MKDIR] Created Dir: E: / Tutorial / Javaexample / Dist

Compile:

[Javac] Compiling 10 Source Files To E: / Tutorial / Javaexample / Build

Dist:

[jar] building jar: E: /Tutorial/javaexample/dist/package-20031217.jar

[jar] building jar: E: /Tutorial/javaexample/dist/package-src-20031217.jarbuild successful

Total Time: 5 Seconds

Note that the JAR file is named based on the current date and sets a list entry for the application's primary class so that the primary class can run directly through a simple command java -jar package-20031217.jar. We also created a JAR file, which only contains the source code of the project.

File system operation

Introduction

We understand enough knowledge about Ant, and now you can generate a basic Java project, but the reality project is of course as simple as our example. In the following sections, we will examine a number of additional features of Ant, and can use them.

In this section, we will examine how to perform common file operations, such as creating a directory and decompress file. One of the excellent features of Ant is that the task of performing these operations is generally the same on all platforms.

Create and delete a directory

One of the most basic file system operations is to create a directory or folder. The task of doing this work is MKDIR, which is not surprising, it is very similar to the Windows and UNIX / Linux commands with the same name.

First pay attention to / being used as a directory separator, which is a formula for UNIX and Linux. You may think that this is not a very platform-independent, but Ant knows how to handle it and do our proper thing for the platform where it is running, which is the same as that we see when you define location-based properties. We can also use /, regardless of the platform - Ant can handle any form, and can even handle two forms of mixing.

Another useful feature of the MKDIR task is its ability to create them when the parent directory does not exist. Consider the above list, ensemons the Archive directory exists, but the Metals directory does not exist. If you use the mkdir command of the underlying platform, you need to first explicitly create the metals directory, and then call the mkdir command for the second time to create the zinc directory. But Ant tasks are more intelligent than this, it can create these two directories one-time. Similarly, if the target directory already exists, the MKDIR task does not make an error message, but it is only assumed that its work has been completed, so nothing.

The delete directory is also very easy:

This will delete the specified directory along with all the files it contains and the subdirectory. Use the file attribute instead of the DIR property to specify a single file to be deleted.

Copy and mobile files and directories

A copy of the copy of the document in Ant is simple. E.g:

You can also use Move to perform renamed operations instead of copying files:

Another common file system operation is to copy or move files to another. Ant syntax to do this work is also very simple:

By default, Ant only outputs a summary of the mobile and replication operations it performs, including information such as the number of files that have been moved or copied. If you want to see more detailed information, including the file name involved, you can set the Verbose property to true.

Create a compressed zip and tar file

In the previous section, we saw how to create a JAR file. The process of creating other archived files is almost identical. Below is an ANT task for creating a zip file:

The same syntax can also be used to create a TAR file. You can also use Gzip and BZIP tasks to compress files. E.g:

Unzip and extract the files is also simple:

It is also possible to include OverWrite properties to control overlay behavior. The default setting is to override all existing files that match the entry in the archive file being extracted. The relevant task name is Untar, Unjar, Gunzip, and Bunzip2.

Replace the tag in the file

The last file system operation we will be in this section is a Replace task, which performs the lookup and replacement operations in the file. The Token property specifies the string to look up, the Value property specifies a new string, and all instances that look up the tag string are replaced with this new string. E.g:

The replacement will be performed in an appropriate location within the file itself. To provide a more detailed output, you can set the Summary property to true. This will result in the number of missing string instances that the task output is found and replaced.

Other useful tasks and technologies

Introduction

Before examining custom tasks, we first introduce some useful features that have not been encountered. A large number of functions are included in the ANT standard, so it is only selected for several of the most useful features. The pattern matching and file selector is a powerful mechanism, which greatly enhances the functions of some of our tasks; will generate task links and co-work with CVS knowledge base, which is discovered. The main practical applications.

Pattern matching

When the file system task is visited earlier, we only use the files and directories that separately named. However, performing those operations for a set of documents for a set of documents to perform operations, for example, all files ending in .java in a given directory. As the equivalent DOS and UNIX commands provide such a function, Ant also provides such a function. This is done using wildcard characters: *, it matches zero or more characters; and it only matches a character. Thus, all the files ending in .java are all mode * .java.

You can also match the directory execution mode. For example, mode src * / *. Java will match all Java files in any directory with the SRC prefix. There is also another mode structure: **, which matches any number of directories. For example, mode ** / *. Java will match all Java files under the current directory structure. You can use the file system task to use mode, such as nested Fileset elements in a fairly consistent way. Previous, we use this task to copy a single file:

If we want to use a pattern, you can replace the File property as a fileset element as follows:

FileSet By default, FileSet contains all files in the specified src directory, so we use an incrude element to the mode for only the Java file. Similarly, we can add an Exclude element to another mode to potentially eliminate the INCLUDE specified. You can even specify multiple include and Exclude elements; this will get a set of files and directories, which contains a panegroup of all matching items of the include mode, but excludes all matching items of the Exclude mode.

Note that there is a very useful fileset feature, but this feature occasionally confuses for those who don't realize it. This feature is called the default exclusion: the built-in mode list that is automatically excluded from the fileset content. The list includes an entry that matches the directory named CVS, and files ending with ~ characters, they may be a backup file. You usually do not want such files and directories in file system operations, so excluding these files are default behaviors. However, if you really want to select all files and directories in an exception, you can set the defaultexcludes property of the file set to NO.

Use selector

As we have seen, the file set is used to specify a set of files, and the content of this group can be specified using the include and Exclude mode. It is also possible to use include and Exclude to select files using include the special elements called the selector. Below is a list of core selectors available to Ant:

SIZE: This selector is used to select a file according to the byte size of the file (unless you specify a different unit). The attribute is used to set the properties of the comparison (LESS, more or Equal), and the value attribute defines the target size of each file.

Contains: Only files containing a given text string (specified by the Text property) matches this selector. By default, the lookup operation is sensitive; add CaseSensitive = "no" can change the default settings.

FILENAME: Name property Specifies the mode of matching with the file name. It is essentially the same as the include element, as well as the Exclude element when NEGATE = "YES" is specified.

Present: Select the following file from the current directory structure: They have the same name and relative directory structure as files in the specified targetdir directory.

Depend: This selector has the same effect as the Present selector, only the matching files are limited to the corresponding files relative to the TargetDir location, and those that have been modified recently. Date: This selector selects files based on its last modified date. The property specified by the attribute is Before, after or equal, the datetime property specifies the date and time of comparison with it, this date and time has a given fixed format mm / dd / yyyy hh: mm am_or_pm. Note that there is a built-in 2 second offset on the Windows platform to allow the underlying file system inaccuracies - this may result in matching files exceed expectations. The amount of cyclone allowed can be changed (specified in milliseconds) using the Granularity property.

Depth: This selector checks the number of structural hierarchies of each file. MIN and / or MAX properties are used to select files with the number of desired directory hierarchy.

You can also combine selectors by nesting one or more selectors in a selector container. The most commonly used selector container and only select the files it contains all selectors. Other Select Its containers include OR, NOT, NONE, and MAJORITY.

Below is an example of a file set, which selects only those that are more than 512 bytes and contain strings "Hello".

Link to the generated file

There are two ways to generate large projects. One is to make a single generated file to do everything; the other is to call the high-level generated file to call other generated files to perform a specific task, thereby dividing the generation process into many smaller parts.

It is easy to use Ant tasks to call another ANT generation from an ANT generation. In a simple case, you can use the ANTFILE attribute, specify only those generated files to use, and Ant will generate the default target in the generated file. E.g:

Any attribute defined in the parent is defined by default to the child generated file, although this can be avoided by specifying inheritall = "false". It is also possible to pass the explicit attribute by using the Property element - even if INHERITALL is set to false, these properties still apply to the child generation file. This feature is suitable for use in incoming parameters to subconstructive files.

Let us consider an example. Here is a generated file we want to call:

(We have not encountered an Echo task in front - it simply outputs a given message.)

Below is the second generated file called the first generation file, it also gives the first generated file to the Message property:

The output obtained by run the second generated file is as follows:

Buildfile: build.xml

Callsub:

SHOWMESSAGE:

[echo] message = Hello from Parent Build

Build Successful

Total Time: 0 second SECONDS

Use CVS Knowledge Base

CVS is an abbreviation for the Concurrent Versions System (concurrent version control system). It is a source code control system designed to track changes made by many developers. It is very popular and is particularly popular in open source project projects. ANT provides a close integration with CVS. This is very useful for the automated generation environment because a single generated file can also extract one or more modules from the source knowledge base, generate items, even based on changes made since the previous execution generated. Batch file.

Note that in order to use the CVS task in Ant, you will need to install the CVS command on the machine and make it available from the command line. This command includes most of the Linux issued kits; it also uses a variety of forms available - such as part of a valuable Cygwin environment. (See Resources for more information on Cygwin.)

Below is an example of an extraction module from the CVS knowledge base:

Package = "org.eclipse.swt.examples"

DEST = "$ {basedir}" />

The main attributes of the CVS task are CVSROOT, which is a complete reference to the CVS knowledge base, including connection methods and user details. The format of this parameter is as follows:

[: Method:] [[user] [: password] @] Hostname [: [port]] / path / to / repository

In the above example, we connected to the central knowledge base of the Eclipse project as an anonymous user. The other attribute then specifies the module we want to extract and the destination of the extracted file. Extraction is the default operation of the CVS task; other operations can be specified by using the Command property.

See Resources for more information on CVS.

Use custom tasks to expand ANT

Introduction

As we see from the aforementioned sections, Ant is very powerful, with many core tasks covering a wide range of functional sets. It also has many additional tasks that have not been introduced here, plus many optional tasks that provide a wide range of features, as well as other tasks provided as part of the Ant-Contrib project; Finally, the external available is listed on the Apache Ant home page. More tasks. In the face of all these tasks provided by Ant, you seem to never need other tasks, but the real power of Ant is its easy scalability. In fact, it is exactly what this scalability has developed so many additional tasks. There may be such an occasion, which is more appropriate to create a custom task in such an occasion. For example, suppose you create a command line tool to perform a specific action; this tool may be the right candidate for the task available to Ant (when the tool is written in java language, although the tool is not It must be written in Java language.) Instead to adjust the tool externally using the EXEC task (this will introduce dependencies, and make generated files more difficult to use when crossing different platforms), you can merge it directly into the generated file in. It is also possible to make Ant's conventional file sets and wildcard matching features to customize tasks.

In this section, we will examine the construction process of a simple custom task. This task will perform a sorting operation on the rows in the file and write the sorted rows into a new file.

Create a custom task

To achieve a simple custom task, what we need is to expand the org.apache.tools.nt.task class, and rewrite the execute () method. Therefore, as a framework for this file, we will prepare the following code:

Import org.apache.tools.nt.buildexception;

Import org.apache.tools.ant.task;

Public class filesorter extends task {

// the normal executing the task

Public void execute () throws buildexception {}

}

Note We declare that the execute () method throws a buildexception exception. If this task has any errors, we will throw this exception to point out the fault to Ant.

Most tasks, whether it is a core task or a custom task, use properties to control their behavior. For this simple task, we need an attribute to specify files to be sorted, and another property is required to specify the output of the sorting content. We call these two attributes called File and Tofile, respectively.

ANT makes it easy to support the properties in custom tasks. To this end, we only need to implement a method with a particularly formatted name, and Ant can call this method using the value of the corresponding attribute specified in the generated file. The name of this method needs to be the name of the set, so in this example, we need a way to setfile () and settofile (). When Ant encounters an attribute setting in the generated file, it looks for a method (called Setter method) with the appropriate name in the relevant task.

The properties in the generation file are specified as a string, so the parameters of our setter method can be a string. In this case, the ANT will use the character string value of the attribute to call our method after any attributes referenced by the expand value. But sometimes we want to treat the value of the property as a different type. The sample task here is this situation, where the attribute value references files on the file system, not just to reference any string. This can be easily done by declaring the method parameters as java.io.file type. Ant will accept the character string value of the attribute and interpret it as a file and pass it to our method. If the file is specified using a relative path name, it is converted to an absolute path relative to the project base directory. Ant can perform similar conversions such as Boolean and int types for other types. If you have two ways with the same name but have different parameters, Ant will use a clearer way, so the file type will take precedence over string type. Two setter methods that this custom task need is similar to:

// the setter for the "file" attribute

Public void setfile (file file) {}

// the setter for the "Tofile" Attribute

Public void settofile (file towile) {}

Realize custom tasks

Using the frame developed in the previous section, now we can complete this simple file sorting task:

Import java.io. *;

Import java.util. *;

Import org.apache.tools.nt.buildexception;

Import org.apache.tools.ant.task;

/ **

* A Simple Example Task to Sort A File

* /

Public class filesorter extends task {

PRIVATE FILE, TOFILE

// the normal executing the task

Public void execute () throws buildexception {

System.out.println ("Sorting File =" File;

Try {

BufferedReader from =

New BufferedReader (New FileReader (File);

Bufferedwriter to =

New BufferedWriter (New FileWriter);

List alllines = new arraylist ();

// read in The Input File

String line = from.readline ();

While (line! = null) {

Alllines.Add (line);

Line = from.readline ();

}

From.Close ();

// sort the list

Collects.Sort (AllLines);

// write out the sorted list

For (Listiterator i = alllines.listiterator (); i.hasnext ();) {

String s = (string) i.next ();

TO.WRITE (S); to.Newline ();

}

TO.CLOSE ();

} catch (filenotfoundexception e) {

Throw New BuildException (e);

} catch (ioexception e) {

Throw New BuildException (e);

}

}

// the setter for the "file" attribute

Public void setfile (file file) {

THIS.FILE = file;

}

// the setter for the "Tofile" Attribute

Public void settofile (file towile) {

THIS.TOFILE = Tofile;

}

}

Two setter methods simply on the value of the attribute so that these values ​​can be used in the execute () method. Here, the input file is entered into a list one by line, then sorted and outputted to the output file in line. Note that in order to simply, we rarely perform an error check - for example, we don't even check if the file is set to set the necessary properties. However, we can't capture at least the I / O exception thrown by the operation, and re-throwing these exceptions as buildexceptions.

You can now use the Javac compiler or compile this custom task from an IDE. In order to resolve the reference problem of the Ant class used, you need to add the location of the Ant.jar file to the classpath. This file should be in the LIB directory under the Ant installation path.

Use custom tasks

Now we have developed and compiled this custom task, and you can use it from the generated file.

Before you can call the custom task, we need to specify a name to define it and tell Ant to implement the information of the class file that implements this task, as well as any ClassPath settings necessary to locate the class file. This is done using the taskdef task, as shown below:

ClassName = "FilesORTER"

ClassPath = "." />

Datual! You can now use this custom task like a core task using Ant. Below is a complete generated file, which shows the definition and usage of this custom task:

ClassName = "FilesORTER

ClassPath = "." />

Now create an Input.txt file in the current working directory to test this custom task. E.g:

Hello there

This is a line

And Here Is Another One

Below is the console output generated after running the above generation file:

Buildfile: build.xml

MAIN:

[FilesORTER] Sorting file = E: /TUTORIAL/CUSTOM/INPUT.TXT

Build Successful

Total Time: 0 second SECONDS

Note that the relative path name of INPUT.TXT is converted into an absolute path name in the current directory. This is because we specify the parameters of the setter method as java.io.file types rather than java.lang.string types. Now look at whether this task is actually working. At this time, you should have created a file called Output.txt in the same directory, which contains the following:

And Here Is Another One

Hello there

This is a line

You can try to specify a non-existing input file to determine how this task is reported to the Ant Report "File Not Found" exception.

Congratulations: You have now developed and used a custom Ant task! Creating a more complex task involves many other aspects, and the reference data contains links to further information sources to this topic.

Reference

Access the Apache Ant home page. This is an excellent source of information, which includes downloads, ANT manuals, and links to other reference materials.

Find more information about the IDE and editor integration of Ant.

Learn more about Eclipse This universal tool platform.

The developerWorks Open Source Project Zone contains rich Eclipse-based content.

If you are an XML newbie, visit the developerWorksxml area.

Cygwin is a class Linux environment for Windows.

Open standards for CVS version control.

Learn more about WebSphere Studio Application Developer, it is based on the Eclipse platform.

Find more information about WebSphere Application Serverant's support for Ant tasks.

Explore the power of JAR file format in "Jar Files Revealed" (developerWorks, October 2003).

DeveloperWorks specially contributed a lot of articles about Ant:

"Incremental Development with Ant and Junit", Malcolm Davis writes (November 2000).

"Extending Ant To Support Interactive Builds", Anthony Young-Garner written (November 2001).

"Enhance Ant with XSL Transformations", JIM CREASMAN writes (September 2003).

Ant also supports open source JIKES compiler and GNU Compiler For Java (GCJ).

In the developerWorks Java technology zone, you can find hundreds of articles about all aspects of Java programming.

You can also refer to the Java Technology Access Tutorial homepage, get a complete list of free Java related tutorials from developerWorks.

转载请注明原文地址:https://www.9cbs.com/read-11896.html

New Post(0)