Не удалось выполнить цель org.codehaus.mojo:exec-maven-plugin:1.3.2:exec (по умолчанию) в проекте mavenproject2:

Я начинаю первоначальную попытку использовать Vert.x в Java. IDE — это Netbeans версии 8.1. Vert.x — это версия 3.0.0. Код для этого проекта показан ниже. Файл pom.xml также указан ниже. Этот код будет работать в среде IDE Netbeans, но сборка (для jar-файла) не будет завершена без ошибки, показанной в ОТЧЕТЕ О СБОРКЕ ниже. Таким образом, сгенерированный файл jar не будет выполняться. Я исследовал все ресурсы, которые мог найти в Интернете, и не могу найти адекватного решения/ответа. Я был бы признателен за любую помощь, которую кто-либо может предложить для решения этой проблемы.

Файл POM создается средой IDE Netbeans при создании нового проекта: Файл — Новый проект — Maven — Проект из архетипа — vertx-java-archetype Затем я добавил метод main().

ПОДРОБНЫЙ ОТЧЕТ ОБ ОШИБКАХ СБОРКИ:

    --- maven-jar-plugin:2.3.2:jar (default-jar) @ mavenproject2 ---
    Building jar: C:\Projects\GenMatchJ\mavenproject2\target\mavenproject2-1.0-SNAPSHOT.jar

    --- maven-shade-plugin:2.3:shade (default) @ mavenproject2 ---
    Including io.vertx:vertx-core:jar:3.0.0 in the shaded jar.
    Including io.netty:netty-common:jar:4.0.28.Final in the shaded jar.
    Including io.netty:netty-buffer:jar:4.0.28.Final in the shaded jar.
    Including io.netty:netty-transport:jar:4.0.28.Final in the shaded jar.
    Including io.netty:netty-handler:jar:4.0.28.Final in the shaded jar.
    Including io.netty:netty-codec:jar:4.0.28.Final in the shaded jar.
    Including io.netty:netty-codec-http:jar:4.0.28.Final in the shaded jar.
    Including com.fasterxml.jackson.core:jackson-core:jar:2.5.3 in the shaded jar.
    Including com.fasterxml.jackson.core:jackson-databind:jar:2.5.3 in the shaded jar.
    Including com.fasterxml.jackson.core:jackson-annotations:jar:2.5.0 in the shaded jar.
    Including io.vertx:vertx-web:jar:3.0.0 in the shaded jar.
    Including io.vertx:vertx-auth-common:jar:3.0.0 in the shaded jar.

    --- exec-maven-plugin:1.3.2:exec (default) @ mavenproject2 ---
    ------------------------------------------------------------------------
    BUILD FAILURE
    ------------------------------------------------------------------------
    Total time: 3.290s
    Finished at: Sun Jun 05 13:01:40 EDT 2016
    Final Memory: 30M/313M
    ------------------------------------------------------------------------
    Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.3.2:exec (default) on project mavenproject2: The parameters 'executable' for goal org.codehaus.mojo:exec-maven-plugin:1.3.2:exec are missing or invalid -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginParameterException

ФАЙЛ POM.XML:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ssp</groupId>
  <artifactId>mavenproject2</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>io.vertx</groupId>
        <artifactId>vertx-dependencies</artifactId>
        <version>3.0.0</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>


  <dependencies>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-core</artifactId>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.3</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <manifestEntries>
                    <Main-Class>io.vertx.core.Starter</Main-Class>
                    <Main-Verticle>com.ssp.mavenproject2.Main</Main-Verticle>
                  </manifestEntries>
                </transformer>
                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/services/io.vertx.core.spi.VerticleFactory</resource>
                </transformer>
              </transformers>
              <artifactSet></artifactSet>
              <outputFile>${project.build.directory}/mavenproject2-${project.version}-fat.jar</outputFile>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.3.2</version>
        <executions>
          <execution>
            <phase>verify</phase>
            <goals>
              <goal>exec</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>io.vertx.core.Starter</mainClass>
          <additionalClasspathElements>
            <additionalClasspathElement>${basedir}/src/main/java/</additionalClasspathElement>
          </additionalClasspathElements>
          <systemProperties>
            <systemProperty>
              <key>vertx.deployment.options.redeploy</key>
              <value>true</value>
            </systemProperty>
            <systemProperty>
              <key>vertx.deployment.options.redeployScanPeriod</key>
              <value>100</value>
            </systemProperty>
          </systemProperties>
          <arguments>
            <argument>run</argument>
            <argument>com/ssp/mavenproject2/Main.java</argument>
            <!--                  <argument>-cluster</argument>
            <argument>-cluster-host</argument>
            <argument>127.0.0.1</argument>-->
          </arguments>
        </configuration>
      </plugin>
    </plugins>
  </build>
    <name>MainSsp</name>
    <description>Main entry point for SSP Example with embedded Vert.x</description>
</project>

ИСХОДНЫЙ КОД:

package com.ssp.mavenproject2;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;

import javax.swing.JOptionPane;


/**
 *
 */
public class Main extends AbstractVerticle {

  public static void main(String[] args) {


      JOptionPane.showMessageDialog(null, "This Vert.x/Java integration is UUUGGGGHH tough without documentation...");


      // Create an HTTP server which simply returns "Hello World!" to each request.
      Vertx.vertx().createHttpServer().requestHandler(req -> req.response().end("Hello World!")).listen(8080);

      Vertx.vertx().setPeriodic(3000, res -> {
        System.out.println("Periodic event triggered.");
      });

      try{

          Thread.sleep(30000);
      }catch(Exception e)
      {
         System.out.println("Exception caught");
      }
  }  

  @Override
  public void start() throws Exception {
    vertx.setPeriodic(3000, res -> {
      System.out.println("Periodic event triggered.");
    });
  }

}

person Rsh At The Fort    schedule 05.06.2016    source источник


Ответы (2)


Похоже, вы пытаетесь запустить mvn exec:exec, но для этого вам нужно указать исполняемый файл (ошибка, которую вы получаете). В этом случае исполняемый файл должен быть вашим двоичным файлом Java, например: /usr/java/latest/bin/java, если вы используете Linux и Oracle RPM.

В качестве альтернативы вы должны сделать: mvn exec:java, который знает, что исполняемым файлом является java, и знает, как выбрать зависимости пути к классам из файла pom.

Теперь, если вы обратите внимание на свой код, вы увидите, что метод public static void main никогда не вызывается, ваш плагин exec использует стартер vert.x, а не ваш класс, поэтому при запуске вашего приложения не будет никакого сервера, только периодический код выполняется внутри метода start.

Если вы выполняете свой основной, то вам все еще не хватает для развертывания вашей вертикали, поэтому у вас есть сервер, но нет периодической задачи, для этого вам нужно добавить:

vertx.deployVerticle(Main.class.getName());
person Paulo Lopes    schedule 09.06.2016
comment
Замена '‹goal›exec‹\goal›' на '‹goal›java‹\goal›' приводит к успешному созданию распространяемого jar-файла, что нормально. Однако, когда я оставляю '‹goal›exec‹\goal›' в файле .pom, эта ошибка возникает при сборке проекта (я использую среду IDE Netbeans для разработки и компиляции кода). Мне не удалось вставить исполняемый файл в этот файл .pom. Я не смог определить, куда следует поместить спецификацию и нужен ли ей только путь или путь + имя файла. - person Rsh At The Fort; 11.06.2016
comment
Еще один комментарий. Спасибо за подсказку/рекомендацию по синтаксису относительно поведения исполняемого кода и развертывания вершин в основном методе. Упомянутое вами поведение соответствует поведению при выполнении кода; работа в среде IDE приводит к вызову функции main() и отсутствию периодической задачи. При выполнении из командной строки выполняется стартер vert.x и нет сервера, только периодический таймер. - person Rsh At The Fort; 11.06.2016

Разрешить Netbeans индексировать репозиторий maven в

~\.m2\repository\org\codehaus\mojo

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

person agcala    schedule 04.04.2018