Apache ant установка windows

Содержание
  1. Инструкция по работе с Apache ANT
  2. Что такое Apache Ant Build Tool?
  3. Зачем использовать инструмент сборки как ANT?
  4. История Apache Ant
  5. Особенности Apache Ant
  6. Установка и настройка Apache Ant
  7. Пример Apache ANT
  8. Структура проекта
  9. Проект:
  10. Задания:
  11. Лучшие практики использования
  12. Преимущества использования
  13. Apache Ant – быстрый старт
  14. 1. Скачиваем, устанавливаем, проверяем
  15. 2. Пишем HelloWorld сценарий
  16. 3. Основные принципы работы
  17. 4. Минимально необходимый список заданий (tasks)
  18. 5. Сценарий для сборки и тестирования Java проекта
  19. How to install Apache Ant on Windows
  20. 1. JAVA_HOME
  21. 2. Download Apache Ant
  22. 3. Add ANT_HOME
  23. 4. Update PATH
  24. 5. Verification
  25. References
  26. mkyong
  27. Installing Apache Ant
  28. Getting Apache Ant
  29. The Short Story
  30. Binary Distribution
  31. Binary RPM Package
  32. Bundled in IDEs
  33. Bundled in Java Applications
  34. Source Distribution
  35. Archive Download Area Layout
  36. System Requirements
  37. Open Source Java Runtimes
  38. Installing Ant
  39. Windows 95, Windows 98 & Windows ME Note
  40. Setup
  41. Windows Note
  42. Check Installation
  43. Optional Tasks
  44. The CLASSPATH Environment Variable
  45. Proxy Configuration
  46. Windows and OS/2
  47. Linux/Unix (bash)
  48. Linux/Unix (csh)
  49. RPM version from jpackage.org
  50. Advanced
  51. Building Ant
  52. Library Dependencies
  53. Troubleshooting
  54. Diagnostics
  55. User Mailing List

Инструкция по работе с Apache ANT

Инструмент сборки — это инструмент программирования, который используется для создания новой версии программы. Он автоматизирует создание исполняемого приложения из любого исходного кода.

Что такое Apache Ant Build Tool?

Ant — это сокращение от Another Neat Tool. Это инструмент сборки на основе XML, который является широко используемым инструментом сборки на основе Java с полной переносимостью чистого кода Java. Например, он позволяет разработчикам применять гибкие принципы и позволяет разрабатывать на основе тестов. Вы можете использовать его для всех повторяющихся задач. Например, создание документации.

Зачем использовать инструмент сборки как ANT?

Вот важные плюсы использования инструмента Build:

История Apache Ant

Вот важные исторические вехи инструмента Apache Ant:

Особенности Apache Ant

Вот основные функции Apache Ant:

Установка и настройка Apache Ant

Мы предполагаем, что вы уже загрузили и установили Java Development Kit (JDK) на свой компьютер. Убедитесь, что для переменной среды JAVA_HOME задана папка, в которой установлен JDK.

Шаг 1) Загрузите файлы с https://ant.apache.org/bindownload.cgi

Шаг 2) Распакуйте этот zip-файл в удобную папку c: \. Использование Winzip, WinRAR, 7-zip или аналогичных инструментов.

Шаг 3) Создайте переменную среды для «ANT_HOME» и присвойте значение переменной местоположению папки Ant.

Шаг 4) Нажмите «Расширенные настройки системы».

Шаг 5) Нажмите на вкладку «Дополнительно».

Шаг 6) Нажмите кнопку «Переменные среды…».

Шаг 7) Нажмите «Создать», чтобы создать новую пользовательскую переменную.

Шаг 8) Введите данные новой пользовательской переменной

Шаг 9) Нажмите кнопку «ОК».

Шаг 10) Нажмите «ОК», чтобы закрыть экран.

Вы увидите следующий экран:

Пример Apache ANT

Давайте сохраним это как «buildl.xml»

Структура проекта

Каждая сборка будет содержать три узла:

Проект:

Все внутри файла сборки в Apache ANT находится в проекте.

Target — это набор задач, который определяется для получения определенного состояния процесса сборки.

Задания:

Это кусок кода, который может быть выполнен. Задача имеет несколько аргументов или атрибутов.

Общий шаблон метода для написания задачи:

Вы можете использовать сборку в задаче или создать свою задачу.

Лучшие практики использования

Вот несколько рекомендаций по использованию Apache Ant.

Преимущества использования

Вот преимущества и преимущества использования Apache Ant:

Источник

Apache Ant – быстрый старт

Apache Ant должен быть знаком каждому Java-программисту: это популярный инструмент сборки ПО (build tool), полностью написанный на Java. Ant использует сценарий, который является обычным XML-файлом. Несмотря на его Java-направленность, веб-разработчики тоже используют этот инструмент.

1. Скачиваем, устанавливаем, проверяем

Linux: устанавливаем из репозитария командой вроде sudo apt-get install ant (замените apt-get на yum если необходимо). Важно: нам нужна версия не ниже 1.8.*. В репозитарии CentOS 6.8 версия 1.7.1, поэтому лучше использовать скрипт, описанный в предыдущей статье.

Windows: посещаем веб-сайт ant.apache.org, заходим в раздел Download/Binary Distributions и скачиваем архив apache-ant-1.10.1-bin.zip (возможно сейчас есть уже более свежая версия). Содержимое архива копируем в любой каталог, например в «C:\Program Files\Apache Ant». Затем добавляем путь к каталогу bin (C:\Program Files\Apache Ant\bin) в системную переменную Path.

Проверяем работоспособность, вызвав ant в командной строке:

Если аналогичное сообщение получено – всё в порядке.

2. Пишем HelloWorld сценарий

Создаём в домашнем каталоге подкаталог hello (в Linux это делает команда mkdir, в Windows – md) и сохраняем туда файл с именем build.xml, содержащий предложенный выше сценарий. Переходим в этот каталог и вызываем ant:

$ mkdir hello
$ cd hello
$ ant
Buildfile: /home/lamp/hello/build.xml

hello:
[echo] Hello, World!
BUILD SUCCESSFULL

Total time: 0 seconds

3. Основные принципы работы

В target есть возможность указать зависимость с помощью атрибута depends. Зависимости связывают target’ы между собой. Например, есть target c именем “compile”, а есть – с именем “run”, зависимый от “compile”. И если мы захотим выполнить “run”, сначала выполнится “compile”.

4. Минимально необходимый список заданий (tasks)

Стандартная версия Ant содержит более 150 заданий (https://ant.apache.org/manual/tasklist.html). Нам пока потребуются только семь:

5. Сценарий для сборки и тестирования Java проекта

И сохраняем туда файл HelloWorld.java следующего содержания:

А затем немного усложняем текст нашего сценария (build.xml):

Запускаем сценарий без параметров и видим результат работы Java программы: Hello, World!

Прямое указание имен каталогов не говорит о хорошем стиле. Особенно если имена в сценарии повторяются. Модифицируем build.xml, используя property (обратите внимание, как нам пригодилось имя проекта, заданное в project) и добавив пару комментариев:

Теперь добавим в сценарий target package для формирования jar файла:

и убедимся что всё работает:

Перейдём к тестированию. Изменим код проекта (чтобы было что тестировать):

и добавим в каталог src файл/класс TestHello.java с простым тестом:

Используя информацию со страницы https://github.com/junit-team/junit4/wiki/getting-started скачиваем два файла, junit-4.12.jar и hamcrest-core-1.3.jar и копируем их в каталог нашего JDK/jre/lib/ext (такую команду копирования используем в CentOS 6.8):

Добавляем в наш сценарий ещё один target – test:

и дополняем строку в target package (jar):

Теперь к списку команд нашего сценария (compile, run, package, clean) добавилась test.
В заключение меняем код нашего проекта так, чтобы приветствие выводилось в отдельном графическом окне. Затем формируем jar файл и запускаем его двойным кликом мыши (у вас должно быть настроено выполнение jar файлов по двойному клику).

Третья версия Java кода:

Слегка дополняем сценарий (в target run), дописав fork=«true» (запуск выполнения класса в другой виртуальной машине). В противном случае run не сработает (проверено экспериментально):

Выполняем команду формирования jar файла ($ ant package), открываем в проводнике файлов каталог

Источник

How to install Apache Ant on Windows

To install Apache Ant on Windows, you just need to download the Ant’s zip file, and Unzip it, and configure the ANT_HOME Windows environment variables.

Читайте также:  Csr bluetooth chip драйвер windows 7

1. JAVA_HOME

Make sure JDK is installed, and JAVA_HOME is configured as Windows environment variable.

2. Download Apache Ant

Assume you unzip to this folder – C:\apache-ant-1.9.4

3. Add ANT_HOME

Add ANT_HOME as the Windows environment variable, and point it to your Ant folder.

4. Update PATH

Update PATH variable, append %ANT_HOME%\bin at the end, so that you can run the Ant’s command everywhere.

5. Verification

If you see a similar message above, means the Apache Ant is installed successfully on Windows.

References

mkyong

Thanks for tutorial.
Did you know what is explanation for?

Trying the default build file: build.xml
Buildfile: build.xml does not exist!
Build failed

Thanks, saved my sunday

Thank you! Mkyong.com rules. Best answers for my googles searches (on Java subject) usually goes for this site. Nice work! Congratulations.

Nice tutor. worked well.

THANK YOU ORIENT MASTER

Thank you! Seriously, the Apache Ant site should just link to this page for the install instructions.

i get createprocess error=2 on building tasks, help could be appreciated

I had to restart my machine after making changes to environment variables.

Thank you for the excellent tutorials. You are a stand-up guy who has helped many. A good model for us to follow!

Thank you for clear instructions.

Excellent Tutorial. Thank you very much

can you also provide the reference for msbuild Ant tutorial

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

Please help me, i got it while i am doing according your instructions….

When i verify I am getting the following exception:

Источник

Installing Apache Ant

Getting Apache Ant

The Short Story

To get up and running with the binary distribution of Ant quickly, follow these steps:

Note that the links in the list above will give more details about each of the steps, should you need them. Or you can just continue reading the rest of this document.

The short story for working with the Ant source code (not needed if you are working with the binary distribution) is:

For the full story, continue reading.

Binary Distribution

The latest stable version of Ant is available from the Ant web page https://ant.apache.org/

The binary distribution of Ant is available as 3 different archives

Choose the format that is best supported for your platform.

Binary RPM Package

Consult the jpackage section below.

Bundled in IDEs

All the main Java IDEs ship with Ant, products such as Eclipse, NetBeans and IntelliJ IDEA. If you install Ant this way you usually get the most recent release of Ant at the time the IDE was released. Some of the IDEs (Eclipse and NetBeans in particular) ship with extra tasks that only work if IDE-specific tools are on Ant’s path. To use these on command-line versions of Ant, the relevant JARs need to be added to the command-line Ant as extra libraries/tasks. Note that if it is an IDE task or extension that is not behaving, the Ant team is unable to field bug reports. Try the IDE mailing lists first, who will cross-file bugs if appropriate.

IDEs can invariably be pointed at different Ant installations. This lets developers upgrade to a new release of Ant, and eliminate inconsistencies between command-line and IDE Ant.

Bundled in Java Applications

Source Distribution

If you prefer the source distribution, you can download the source for the latest Ant release from https://ant.apache.org/srcdownload.cgi.

If you prefer the leading-edge code, you can access the code as it is being developed via Git. The Ant website has details on accessing Git. All bug fixes will go in against the HEAD of the source tree, and the first response to many bug reports will be «have you tried the latest version». Don’t be afraid to download and build a prerelease distribution, as everything other than new features are usually stable.

See the section Building Ant on how to build Ant from the source code. You can also access the Ant Git repository on-line.

Archive Download Area Layout

Older versions of Ant are available in the archives at https://archive.apache.org/dist/ant/. The files are organized as follows.

Filename or Path Description
KEYS PGP keyfile. It contains the PGP keys of Ant developers so you can ‘trust’ the distribution.
RELEASE-NOTES-.html Release notes of the given version in HTML format. When upgrading your Ant installation you should have a look at the Changes that could break older environments section.
ant-current-bin.zip ZIP archive containing the compiled version of Ant in the last released version. It is recommended that you do not download the latest version this way, as the standard way of downloading described above will redirect you to a mirror closer to you, thus making the download faster for you and reducing the load on Apache servers.
ant-current-src.zip ZIP archive containing the sources of Ant. If you have this you can compile Ant. If you do not have the required dependencies, the classes depending on them are just not built. Again, it is preferred to use the standard way of getting the source package described above to make your download quicker and to reduce the load on Apache servers.
ant-current-*.asc Security file for checking the correctness of the zip file. This one is the PGP signature.
ant-current-*.md5 Security file for checking the correctness of the zip file. This one is the MD5 checksum.
ant-current-*.sha1 Security file for checking the correctness of the zip file. This one is the SHA1 checksum.
ant-current-*.sha512 Security file for checking the correctness of the zip file. This one is the SHA512 checksum.
antlibs/ This directory holds the Antlibs that are made of available by the Apache Ant project. Antlibs are bundles of Ant tasks that are not delivered as part of the Ant core but are available as optional downloads.
binaries/ The binaries directory holds specific Ant releases bundled in both ZIP and tar.gz archive formats. The named releases are in contrast to the ant-current-bin.zip file in the parent directory, which is always guaranteed to be the most current release of Ant.
common/ The common directory holds various files, such as the Apache License file that Ant is licensed under, that people may wish to examine without having to download the whole Ant distribution.
source/ The source directory holds the source code for specific Ant releases bundled in both ZIP and tar.gz archive formats. The named releases are in contrast to the ant-current-src.zip file in the parent directory, which is always guaranteed to hold the source code for the most current release of Ant.

System Requirements

Ant has been used successfully on many platforms, including Linux, commercial flavours of Unix such as Solaris and HP-UX, macOS, Windows NT descendants, OS/2 Warp, Novell Netware 6, OpenVMS. The platforms used most for development are, in no particular order, Linux, macOS, Microsoft Windows and Unix; these are therefore that platforms that tend to work best. Since Ant 1.7, Windows 9x is no longer supported.

For the current version of Ant (1.10), you will also need a JDK installed on your system, version 8 or later required. The more up-to-date the version of Java, the more Ant tasks you get.

Note: If a JDK is not present, only the runtime (JRE), then many tasks will not work.

Note: Ant 1.9.* works with JDK 1.5 and higher, Ant 1.8.* works with JDK 1.4 and higher, Ant 1.7.* works with JDK 1.3 and higher, Ant 1.6.* works with JDK 1.2 and higher, Ant 1.2 to Ant 1.5.* work with JDK 1.1 and higher.

Open Source Java Runtimes

The Ant team strongly supports users running Ant on OpenJDK and other open source Java runtimes, and so strives to have a product that works well on those platforms.

Installing Ant

The binary distribution of Ant consists of the following directory layout:

Only the bin and lib directories are required to run Ant.

Windows 95, Windows 98 & Windows ME Note

On these systems you will also need to configure more environment space to cater for the environment variables used in the Ant launch script. To do this, you will need to add or update the following line in the config.sys file

Setup

Before you can run Ant there is some additional setup you will need to do unless you are installing the RPM Version from jpackage.org:

Operating System-specific instructions for doing this from the command line are in the Windows, Linux/Unix (bash), and Linux/Unix (csh) sections. Note that using this method, the settings will only be valid for the command line session you run them in.

Note: Do not install Ant’s ant.jar file into the lib/ext directory of the JDK/JRE. Ant is an application, whilst the extension directory is intended for JDK extensions. In particular there are security restrictions on the classes which may be loaded by an extension.

Windows Note

Check Installation

If this does not work, ensure your environment variables are set right. E.g., on Windows, they must resolve to:

Optional Tasks

Ant supports a number of optional tasks. An optional task is a task which typically requires an external library to function. The optional tasks are packaged together with the core Ant tasks.

The external libraries required by each of the optional tasks is detailed in the Library Dependencies section. These external libraries must be added to Ant’s classpath, in any of the following ways:

In the CLASSPATH environment variable. Avoid this; it makes the JAR files visible to all Java applications, and causes no end of support calls. See below for details.

In some accepted by the task itself. Since Ant 1.7.0, you can run the task without junit.jar in Ant’s own classpath, so long as it is included (along with your program and tests) in the classpath passed when running the task.

Where possible, this option is generally to be preferred, as the Ant script itself can determine the best path to load the library from: via relative path from the basedir (if you keep the library under version control with your project), according to Ant properties, environment variables, Ivy downloads, whatever you like.

To do so, change to the ANT_HOME directory and execute the command:

where option is one of the following, as described above:

You may also need to set proxy settings. See the Proxy Settings section for details.

The Apache Ant Project also provides additional tasks and types that are available as separately downloaded Ant Libraries. You can see the the list of available Antlibs at the Ant Libraries page.

You can also find tasks and types provided by third-party projects at the External Tools and Tasks page.

IDEs have different ways of adding external JAR files and third-party tasks to Ant. Usually it is done by some configuration dialog. Sometimes JAR files added to a project are automatically added to Ant’s classpath.

The CLASSPATH Environment Variable

The CLASSPATH environment variable is a source of many Ant support queries. As the round trip time for diagnosis on the Ant user mailing list can be slow, and because filing bug reports complaining about ‘ant.bat’ not working will be rejected by the developers as WORKSFORME «this is a configuration problem, not a bug», you can save yourself a lot of time and frustration by following some simple steps.

You can also make your Ant script reject this environment variable just by placing the following at the top of the script (or in an init target):

Proxy Configuration

Many Ant built-in and third-party tasks use network connections to retrieve files from HTTP servers. If you are behind a firewall with a proxy server, then Ant needs to be configured with the proxy. Here are the different ways to do this.

These are documented in Java’s Networking Properties, and control the proxy behaviour of the entire JVM. To set them in Ant, declare them in the ANT_OPTS environment variable. This is the best option for a non-mobile system. For a laptop, you have to change these settings as you roam. To set ANT_OPTS :

For Windows, set the environment variable in the appropriate dialog box and open a new console or, by hand

If you are writing a build file that is always to be used behind the firewall, the setproxy task lets you configure the proxy (which it does by setting the JVM properties). If you do this, we strongly recommend using Ant properties to define the proxy host, port, etc, so that individuals can override the defaults.

The Ant team acknowledges that this is unsatisfactory. Until the JVM automatic proxy setup works properly everywhere, explicit JVM options via ANT_ARGS are probably the best solution. Setting properties on Ant’s command line do not work, because those are Ant properties being set, not JVM options. This means the following does not set up the command line:

All it does is set up two Ant properties.

One other trouble spot with proxies is with authenticating proxies. Ant cannot go beyond what the JVM does here, and as it is very hard to remotely diagnose, test and fix proxy-related problems, users who work behind a secure proxy will have to spend much time configuring the JVM properties until they are happy.

Windows and OS/2

Linux/Unix (bash)

Linux/Unix (csh)

Having a symbolic link set up to point to the JVM/JDK version makes updates more seamless.

RPM version from jpackage.org

The JPackage project distributes an RPM version of Ant. With this version, it is not necessary to set JAVA_HOME or ANT_HOME environment variables and the RPM installer will correctly place the ant executable on your path.

Note: Since Ant 1.7.0, if the ANT_HOME environment variable is set, the JPackage distribution will be ignored.

Optional JARs for the JPackage version are handled in two ways. The easiest, and best way is to get these external libraries from JPackage if JPackage has them available. (Note: for each such library, you will have to get both the external package itself (e.g. oro-2.0.8-2jpp.noarch.rpm ) and the small library that links Ant and the external package (e.g. ant-apache-oro-1.6.2-3jpp.noarch.rpm ).

However, JPackage does not package proprietary software, and since some of the optional packages depend on proprietary JARs, they must be handled as follows. This may violate the spirit of JPackage, but it is necessary if you need these proprietary packages. For example, suppose you want to install support for NetRexx, which JPackage does not support:

Advanced

There are many different ways to run Ant. What you need is at least the following:

Building Ant

To build Ant from source, you can either install the Ant source distribution or clone the Ant repository from Git. See Source Distribution for details.

Once you have installed the source, change into the installation directory.

Set the JAVA_HOME environment variable to the directory where the JDK is installed. See Installing Ant for examples on how to do this for your operating system.

Make sure you have downloaded any auxiliary JARs required to build tasks you are interested in. These should be added to the lib/optional directory of the source tree. See Library Dependencies for a list of JAR requirements for various features. Note that this will make the auxiliary JAR available for the building of Ant only. For running Ant you will still need to make the JARs available as described under Installing Ant.

You can also get most of the auxiliary JAR files (i.e. the JAR files that various optional Ant tasks depend on) by running Ant on the fetch.xml build file. See Optional Tasks for instructions on how to do this.

Since Ant 1.7.0, Ant has a hard dependency on JUnit. The fetch.xml build script will download JUnit automatically, but if you don’t use this you must install it manually into lib/optional (download it from JUnit.org) if you are using a source distribution of Ant.

Your are now ready to build Ant:

This will create a binary distribution of Ant in the directory you specified.

The above action does the following:

On most occasions you will not need to explicitly bootstrap Ant since the build scripts do that for you. However, if the build file you are using makes use of features not yet compiled into the bootstrapped Ant, you will need to manually bootstrap. Run bootstrap.bat (Windows) or bootstrap.sh (UNIX) to build a new bootstrap version of Ant.

If you wish to install the build into the current ANT_HOME directory, you can use:

Ant’s build script will try to set executable flags for its shell scripts on Unix(-like) systems. There are various reasons why the chmod task might fail (like when you are running the build script as a different user than the one who installed Ant initially). In this case you can set the Ant property chmod.fail to false when starting the build like in

and any error to change permission will not result in a build failure.

Library Dependencies

The following libraries are needed in Ant’s classpath if you are using the indicated feature. Note that only one of the regexp libraries is needed for use with the mappers (and Java includes a regexp implementation which Ant will find automatically). You will also need to install the particular Ant optional JAR containing the task definitions to make these tasks available. Please refer to the Installing Ant / Optional Tasks section above.

Troubleshooting

Diagnostics

For diagnostics from within IDE, use the diagnostics task to run the same tests as an Ant option. This can be added to a diagnostics target in a build file to see what tasks are available under the IDE, what the XML parser and classpath is, etc.

User Mailing List

If you cannot get Ant installed or working, the Ant user mailing list is the best place to start with any problem. Please do your homework first, make sure that it is not a CLASSPATH problem, and run a diagnostics check to see what Ant thinks of its own state. Why the user list, and not the developer list? Because there are more users than developers, so more people who can help you.

Please only file a bug report against Ant for a configuration/startup problem if there really is a fixable bug in Ant related to configuration, such as it not working on a particular platform, with a certain JVM version, etc, or if you are advised to do it by the user mailing list.

Источник

Поделиться с друзьями
Советы экспертов и специалистов
Adblock
detector