Maven antrun с последовательным ant-contrib не запускается

У нас есть специальная процедура для разделения файлов в подпапках на расширения, которые будут скопированы и объединены в файлы с одним расширением. Для этого особого подхода я хотел использовать maven-antrun-plugin, для последовательной итерации и упаковки jar через дирсет нам нужна библиотека ant-contrib.

Предстоящая конфигурация плагина завершается с ошибкой. Что я неправильно настроил? Спасибо.

Конфигурация плагина

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-antrun-plugin</artifactId>
  <version>1.6</version>
  <executions>
    <execution>
      <phase>validate</phase>
      <goals>
        <goal>run</goal>
      </goals>
      <configuration>
        <target>
          <for param="extension">
            <path>
              <dirset dir="${basedir}/src/main/webapp/WEB-INF/resources/extensions/">
                <include name="*" />
              </dirset>
            </path>

            <sequential>
              <basename property="extension.name" file="${extension}" />
              <echo message="Creating JAR for extension '${extension.name}'." />
              <jar destfile="${basedir}/target/extension-${extension.name}-1.0.0.jar">
                <zipfileset dir="${extension}" prefix="WEB-INF/resources/extensions/${extension.name}/">
                  <include name="**/*" />
                </zipfileset>
              </jar>
            </sequential>
          </for>
        </target>
      </configuration>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>ant-contrib</groupId>
      <artifactId>ant-contrib</artifactId>
      <version>1.0b3</version>
      <exclusions>
        <exclusion>
          <groupId>ant</groupId>
          <artifactId>ant</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.ant</groupId>
      <artifactId>ant-nodeps</artifactId>
      <version>1.8.1</version>
    </dependency>
  </dependencies>
</plugin>

Ошибка

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.6:run (default) on project extension-platform: An Ant BuildException has occured: Problem: failed to create task or type for
[ERROR] Cause: The name is undefined.
[ERROR] Action: Check the spelling.
[ERROR] Action: Check that any custom tasks/types have been declared.
[ERROR] Action: Check that any <presetdef>/<macrodef> declarations have taken place.
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

person Christopher Klewes    schedule 06.12.2010    source источник


Ответы (4)


Похоже, вам не хватает taskdef, необходимого для объявлять задачи ant-contrib, чтобы Ant знал о них, отсюда и эта часть сообщения об ошибке:

Problem: failed to create task or type for

(Возможно, было бы немного понятнее, если бы неудачная задача — 'for' — была указана в кавычках.)

Один из способов добавить taskdef — вставить его непосредственно перед циклом for:

<target>
    <taskdef resource="net/sf/antcontrib/antlib.xml"
             classpathref="maven.plugin.classpath" />
    <for param="extension">
    ...
person martin clayton    schedule 07.12.2010
comment
Спасибо, это отлично сработало для меня. Я также пробовал это, но использовал неправильную ссылку на путь к классам. - person Christopher Klewes; 07.12.2010

Поэтому я потратил как минимум один час, чтобы найти ошибку с небольшой подсказкой ниже...

Я использую maven3 и все остальное, как описано выше, НО я должен использовать maven.dependency.classpath вместо maven.plugin.classpath! В противном случае maven не найдет задачи contrib. Надеюсь, это поможет кому-нибудь.

person TNI    schedule 26.11.2012

Потратив 2 часа и прочитав слишком много ответов, это то, что мне нужно проверить

http://www.thinkplexx.com/learn/howto/maven2/plugins/could-not-load-definitions-from-resource-antlib-xml-understanding-the-problem-and-fix-worklow

Я напечатал все пути к классам maven, используя это

<property name="compile_classpath" refid="maven.compile.classpath"/>
<property name="runtime_classpath" refid="maven.runtime.classpath"/>
<property name="test_classpath" refid="maven.test.classpath"/>
<property name="plugin_classpath" refid="maven.plugin.classpath"/>
<echo message="compile classpath: ${compile_classpath}"/>
<echo message="runtime classpath: ${runtime_classpath}"/>
<echo message="test classpath:    ${test_classpath}"/>
<echo message="plugin classpath:  ${plugin_classpath}"/>

и проверил, какой путь к классам содержит файл jar antrib. Поэтому я изменил classpathhref на maven.runtime.classpath с maven.plugin.classpath. Итак, мой taskdef

<taskdef resource="net/sf/antcontrib/antcontrib.properties" classpathref="maven.runtime.classpath" />

и зависимости

<dependency>
  <groupId>ant-contrib</groupId>
  <artifactId>ant-contrib</artifactId>
  <version>1.0b3</version>
  <exclusions>
       <exclusion>
          <groupId>ant</groupId>
          <artifactId>ant</artifactId>
       </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.apache.ant</groupId>
  <artifactId>ant-nodeps</artifactId>
  <version>1.8.1</version>
</dependency>
person Sunil Garg    schedule 30.08.2017

Я тоже потратил на это несколько часов, потому что не удалось найти задание antcontrib for.

Наконец-то я узнал, что for задача определена не в antcontrib.properties, а в antlib.xml!

antcontrib.properties — это способ ведения дел, существовавший до версии 1.6. Современный способ — использовать antlib.xml.

Итак, это рабочий пример maven 3.5, ant 1.8:

<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <dependencies>
        <dependency>
            <groupId>ant-contrib</groupId>
            <artifactId>ant-contrib</artifactId>
            <version>1.0b3</version>
            <exclusions>
                <exclusion>
                    <groupId>ant</groupId>
                    <artifactId>ant</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <execution>
        <id>deploy_to_distrib_folder</id>
        <phase>package</phase>
        <configuration>

            <target>
                <taskdef resource="net/sf/antcontrib/antlib.xml" />

                <macrodef name="deploy_extra_dir">
                    <attribute name="dir" />
                    <sequential>
                        <basename property="basename" file="@{dir}" />
                        <sync todir="${outputDir}/${basename}">
                            <fileset dir="@{dir}" />
                        </sync>
                        <var name="basename" unset="true" />
                    </sequential>
                </macrodef>

                <for param="dir">
                    <path>
                        <dirset dir="${project.build.directory}/maven-shared-archive-resources" includes="*" />
                    </path>
                    <sequential>
                        <deploy_extra_dir dir="@{dir}" />
                    </sequential>
                </for>

            </target>
        </configuration>
        <goals>
            <goal>run</goal>
        </goals>
    </execution>
</plugin>

Надеюсь это поможет!

person Sxilderik    schedule 09.11.2018