private MavenExecutionResult doExecute(
      @NotNull final File file,
      @NotNull final List<String> activeProfiles,
      @NotNull final List<String> inactiveProfiles,
      @NotNull final List<String> goals,
      @NotNull final List<String> selectedProjects,
      boolean alsoMake,
      boolean alsoMakeDependents)
      throws RemoteException {
    MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, goals);

    if (!selectedProjects.isEmpty()) {
      request.setRecursive(true);
      request.setSelectedProjects(selectedProjects);
      if (alsoMake && alsoMakeDependents) {
        request.setMakeBehavior(ReactorManager.MAKE_BOTH_MODE);
      } else if (alsoMake) {
        request.setMakeBehavior(ReactorManager.MAKE_MODE);
      } else if (alsoMakeDependents) {
        request.setMakeBehavior(ReactorManager.MAKE_DEPENDENTS_MODE);
      }
    }

    Maven maven = getComponent(Maven.class);
    org.apache.maven.execution.MavenExecutionResult executionResult = maven.execute(request);

    return new MavenExecutionResult(
        executionResult.getProject(), filterExceptions(executionResult.getExceptions()));
  }
Esempio n. 2
0
  @Override
  public void addMarkers(IResource pomResource, String type, MavenExecutionResult result) {
    SourceLocation defaultSourceLocation = new SourceLocation(1, 0, 0);
    List<MavenProblemInfo> allProblems = new ArrayList<MavenProblemInfo>();

    allProblems.addAll(
        toMavenProblemInfos(pomResource, defaultSourceLocation, result.getExceptions()));

    MavenProject mavenProject = result.getProject();
    DependencyResolutionResult resolutionResult = result.getDependencyResolutionResult();
    if (resolutionResult != null) {
      allProblems.addAll(
          toMavenProblemInfos(
              pomResource, defaultSourceLocation, resolutionResult.getCollectionErrors()));
      for (org.eclipse.aether.graph.Dependency dependency :
          resolutionResult.getUnresolvedDependencies()) {
        List<Exception> exceptions = resolutionResult.getResolutionErrors(dependency);
        if (exceptions != null && exceptions.size() > 0) {
          SourceLocation sourceLocation =
              SourceLocationHelper.findLocation(mavenProject, dependency);
          allProblems.addAll(toMavenProblemInfos(pomResource, sourceLocation, exceptions));
        }
      }
    }

    if (mavenProject != null) {
      addMissingArtifactProblemInfos(mavenProject, defaultSourceLocation, allProblems);
    }

    addErrorMarkers(pomResource, type, allProblems);
  }
Esempio n. 3
0
  private int execute(CliRequest cliRequest) {
    MavenExecutionResult result = maven.execute(cliRequest.request);

    if (result.hasExceptions()) {
      ExceptionHandler handler = new DefaultExceptionHandler();

      Map<String, String> references = new LinkedHashMap<String, String>();

      MavenProject project = null;

      for (Throwable exception : result.getExceptions()) {
        ExceptionSummary summary = handler.handleException(exception);

        logSummary(summary, references, "", cliRequest.showErrors);

        if (project == null && exception instanceof LifecycleExecutionException) {
          project = ((LifecycleExecutionException) exception).getProject();
        }
      }

      logger.error("");

      if (!cliRequest.showErrors) {
        logger.error("To see the full stack trace of the errors, re-run Maven with the -e switch.");
      }
      if (!logger.isDebugEnabled()) {
        logger.error("Re-run Maven using the -X switch to enable full debug logging.");
      }

      if (!references.isEmpty()) {
        logger.error("");
        logger.error(
            "For more information about the errors and possible solutions"
                + ", please read the following articles:");

        for (Map.Entry<String, String> entry : references.entrySet()) {
          logger.error(entry.getValue() + " " + entry.getKey());
        }
      }

      if (project != null && !project.equals(result.getTopologicallySortedProjects().get(0))) {
        logger.error("");
        logger.error("After correcting the problems, you can resume the build with the command");
        logger.error("  mvn <goals> -rf :" + project.getArtifactId());
      }

      if (MavenExecutionRequest.REACTOR_FAIL_NEVER.equals(
          cliRequest.request.getReactorFailureBehavior())) {
        logger.info("Build failures were ignored.");

        return 0;
      } else {
        return 1;
      }
    } else {
      return 0;
    }
  }
Esempio n. 4
0
  /**
   * @param goals
   * @param serverProperties
   * @param module
   * @param monitor
   * @return
   * @throws CoreException
   */
  public static boolean runBuild(
      List<String> goals, Properties serverProperties, IModule module, IProgressMonitor monitor)
      throws CoreException {
    IMaven maven = MavenPlugin.getMaven();
    IMavenExecutionContext executionContext = maven.createExecutionContext();
    MavenExecutionRequest executionRequest = executionContext.getExecutionRequest();
    executionRequest.setPom(getModelFile(module));
    if (serverProperties != null && serverProperties.isEmpty() == false) {
      Server fabric8Server = new Server();
      fabric8Server.setId(serverProperties.getProperty(SERVER_ID));
      fabric8Server.setUsername(serverProperties.getProperty(SERVER_USER));
      fabric8Server.setPassword(serverProperties.getProperty(SERVER_PASSWORD));
      executionRequest.addServer(fabric8Server);
    }
    executionRequest.setGoals(goals);

    MavenExecutionResult result = maven.execute(executionRequest, monitor);
    for (Throwable t : result.getExceptions()) {
      Activator.getLogger().error(t);
    }
    return !result.hasExceptions();
  }
  private void logReactorSummary(MavenSession session) {
    logger.info(chars('-', LINE_LENGTH));

    logger.info("Reactor Summary:");

    logger.info("");

    MavenExecutionResult result = session.getResult();

    for (MavenProject project : session.getProjects()) {
      StringBuilder buffer = new StringBuilder(128);

      buffer.append(project.getName());

      buffer.append(' ');
      while (buffer.length() < LINE_LENGTH - 21) {
        buffer.append('.');
      }
      buffer.append(' ');

      BuildSummary buildSummary = result.getBuildSummary(project);

      if (buildSummary == null) {
        buffer.append("SKIPPED");
      } else if (buildSummary instanceof BuildSuccess) {
        buffer.append("SUCCESS [");
        buffer.append(getFormattedTime(buildSummary.getTime()));
        buffer.append("]");
      } else if (buildSummary instanceof BuildFailure) {
        buffer.append("FAILURE [");
        buffer.append(getFormattedTime(buildSummary.getTime()));
        buffer.append("]");
      }

      logger.info(buffer.toString());
    }
  }
Esempio n. 6
0
    private int doExecute(final MavenExecutionRequest request) throws Exception {
      assert request != null;
      assert config != null;

      if (config.isDebug() || config.isShowVersion()) {
        CLIReportingUtils.showVersion(config.getStreams().out);
      }

      //
      // TODO: i18n all of this
      //

      if (request.isShowErrors()) {
        logger.info("Error stack-traces are turned on.");
      }
      if (MavenExecutionRequest.CHECKSUM_POLICY_WARN.equals(request.getGlobalChecksumPolicy())) {
        logger.info("Disabling strict checksum verification on all artifact downloads.");
      } else if (MavenExecutionRequest.CHECKSUM_POLICY_FAIL.equals(
          request.getGlobalChecksumPolicy())) {
        logger.info("Enabling strict checksum verification on all artifact downloads.");
      }

      if (log.isDebugEnabled()) {
        log.debug("Executing request: {}", Yarn.render(request, Yarn.Style.MULTI));
      }

      MavenExecutionResult result;
      Maven maven = container.lookup(Maven.class);
      try {
        result = maven.execute(request);
      } finally {
        container.release(maven);
      }

      if (!result.hasExceptions()) {
        return 0;
      }
      // else process exceptions

      ExceptionHandler handler = new DefaultExceptionHandler();
      Map<String, String> references = new LinkedHashMap<String, String>();
      MavenProject project = null;

      for (Throwable exception : result.getExceptions()) {
        ExceptionSummary summary = handler.handleException(exception);

        logSummary(summary, references, "", request.isShowErrors());

        if (project == null && exception instanceof LifecycleExecutionException) {
          project = ((LifecycleExecutionException) exception).getProject();
        }
      }

      logger.error("");

      if (!request.isShowErrors()) {
        logger.error("To see the full stack-trace of the errors, re-run Maven with the -e switch.");
      }
      if (!logger.isDebugEnabled()) {
        logger.error("Re-run Maven using the -X switch to enable full debug logging.");
      }

      if (!references.isEmpty()) {
        logger.error("");
        logger.error(
            "For more information about the errors and possible solutions, please read the following articles:");

        for (Map.Entry<String, String> entry : references.entrySet()) {
          logger.error(entry.getValue() + " " + entry.getKey());
        }
      }

      if (project != null && !project.equals(result.getTopologicallySortedProjects().get(0))) {
        logger.error("");
        logger.error("After correcting the problems, you can resume the build with the command");
        logger.error("  mvn <goals> -rf :" + project.getArtifactId());
      }

      if (MavenExecutionRequest.REACTOR_FAIL_NEVER.equals(request.getReactorFailureBehavior())) {
        logger.info("Build failures were ignored.");
        return 0;
      } else {
        return 1;
      }
    }
  public void execute() throws MojoExecutionException, MojoFailureException {
    // set up derived paths
    forgeDir = new File(outputDir, "forge");
    jarsDir = new File(forgeDir, "mcp/jars");

    // check whether the artifact is already installed
    if (reinstall) {
      getLog().info("reinstall flag set; skipping availability check");
    } else {
      getLog().info("attempting to resolve Forge artifacts");

      if (null != resolveApiArtifact() && null != resolveToolsArtifact()) {
        getLog().info("artifacts are available; skipping installation");
        return;
      } else {
        getLog().info("artifacts not available; continuing installation");
      }
    }

    if (!noExtract) downloadAndExtract();

    if (!forgeDir.isDirectory())
      throw new MojoFailureException("distribution did not extract to the excpected directory");

    // run the install script
    if (!noInstall) {
      getLog().info("running install script");
      try {
        final PythonLauncher launcher = new PythonLauncher(getLog(), forgeDir);

        final int result = launcher.execute(new File(forgeDir, "install.py"));

        if (0 != result) {
          throw new MojoFailureException("install script returned " + result);
        }
      } catch (IOException caught) {
        throw new MojoFailureException("error calling install script", caught);
      }
    }

    // load Minecraft's POM
    final Model minecraft = loadModelFromResouce("minecraft.pom");
    minecraft.setVersion(getMinecraftVersion());

    // figure out Minecraft's dependencies
    {
      getLog().info("detecting Minecraft dependencies");
      final Artifact lwjgl =
          locator.findVersion(new File(jarsDir, "bin/lwjgl.jar"), "org.lwjgl.lwjgl", "lwjgl");

      final Artifact lwjgl_util =
          new DefaultArtifact("org.lwjgl.lwjgl", "lwjgl_util", "jar", lwjgl.getVersion());

      // don't include jinput.jar
      // it's a transitive dependency from LWJGL

      getLog().info("resolving Minecraft dependencies");
      for (Artifact target : new Artifact[] {lwjgl, lwjgl_util}) {
        getLog().info("    " + target);

        final Artifact resolved = resolveRemoteArtifact(target);
        if (null == resolved)
          throw new MojoFailureException("unable to resolve artifact " + target);

        minecraft.addDependency(artifactToDependency(resolved));
      }
    }

    // install Minecraft JAR
    installJar(minecraft, new File(jarsDir, "bin/minecraft.jar"));

    // figure out Forge's dependencies
    // using a Map of coordinates => artifact for deduplication
    // can't use a Set, Artifact#equals() doesn't behave
    final Map<String, Dependency> forgeDeps = new HashMap<String, Dependency>();
    for (File file : (new File(forgeDir, "mcp/lib")).listFiles()) {
      final Artifact artifact = locator.locate(file);
      if (null == artifact)
        throw new MojoFailureException("no artifact found for dependency " + file.getName());

      forgeDeps.put(artifact.toString(), artifactToDependency(artifact));
    }

    // add Minecraft client to Forge dependencies
    {
      final Artifact artifact =
          new DefaultArtifact("net.minecraft", "minecraft", "jar", getMinecraftVersion());
      forgeDeps.put(artifact.toString(), artifactToDependency(artifact));
    }

    // extract the Forge POM
    final File pom = new File(forgeDir, "pom.xml");
    {
      final Model model = loadModelFromResouce("mcforge.pom");
      model.setVersion(getApiDependency().getVersion());
      model.setDependencies(new ArrayList<Dependency>(forgeDeps.values()));
      writeModelToFile(model, pom);
    }

    // execute a build from the Forge POM
    getLog().info("executing POM to package and install artifacts");
    try {
      final MavenExecutionRequest request = new DefaultMavenExecutionRequest();
      requestPopulator.populateDefaults(request);

      request.setPom(pom);
      request.setGoals(Collections.singletonList("install"));

      final MavenExecutionResult result = maven.execute(request);

      // check for startup exceptions
      if (result.hasExceptions())
        throw new MojoFailureException(
            "failed to package and install artifacts", result.getExceptions().get(0));

      // check for build failure
      final BuildSummary summary = result.getBuildSummary(result.getProject());
      if (summary instanceof BuildFailure) {
        throw new MojoFailureException(
            "failed to package and install artifacts", ((BuildFailure) summary).getCause());
      }
    } catch (MojoFailureException caught) {
      throw caught;
    } catch (Exception caught) {
      throw new MojoFailureException("failed to package and install artifacts", caught);
    }
  }
  @Override
  public void resolveProjectDependencies(
      final IMavenProjectFacade facade,
      Set<Capability> capabilities,
      Set<RequiredCapability> requirements,
      final IProgressMonitor monitor)
      throws CoreException {
    long start = System.currentTimeMillis();
    log.debug("Resolving dependencies for {}", facade.toString()); // $NON-NLS-1$

    markerManager.deleteMarkers(facade.getPom(), IMavenConstants.MARKER_DEPENDENCY_ID);

    ProjectBuildingRequest configuration =
        getMaven().getExecutionContext().newProjectBuildingRequest();
    configuration.setProject(facade.getMavenProject()); // TODO do we need this?
    configuration.setResolveDependencies(true);
    MavenExecutionResult mavenResult =
        getMaven().readMavenProject(facade.getPomFile(), configuration);

    markerManager.addMarkers(facade.getPom(), IMavenConstants.MARKER_DEPENDENCY_ID, mavenResult);

    if (!facade.getResolverConfiguration().shouldResolveWorkspaceProjects()) {
      return;
    }

    MavenProject mavenProject = facade.getMavenProject();

    // dependencies

    // resolved dependencies
    for (Artifact artifact : mavenProject.getArtifacts()) {
      requirements.add(
          MavenRequiredCapability.createMavenArtifact(
              new ArtifactKey(artifact), artifact.getScope(), artifact.isOptional()));
    }

    // extension plugins (affect packaging type calculation)
    for (Plugin plugin : mavenProject.getBuildPlugins()) {
      if (plugin.isExtensions()) {
        ArtifactKey artifactKey =
            new ArtifactKey(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion(), null);
        requirements.add(
            MavenRequiredCapability.createMavenArtifact(
                artifactKey, "plugin", false)); // $NON-NLS-1$
      }
    }

    // missing dependencies
    DependencyResolutionResult resolutionResult = mavenResult.getDependencyResolutionResult();
    if (resolutionResult != null && resolutionResult.getUnresolvedDependencies() != null) {
      for (Dependency dependency : resolutionResult.getUnresolvedDependencies()) {
        org.eclipse.aether.artifact.Artifact artifact = dependency.getArtifact();
        ArtifactKey dependencyKey =
            new ArtifactKey(
                artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), null);
        requirements.add(
            MavenRequiredCapability.createMavenArtifact(
                dependencyKey, dependency.getScope(), dependency.isOptional()));
      }
    }

    log.debug(
        "Resolved dependencies for {} in {} ms",
        facade.toString(),
        System.currentTimeMillis() - start); // $NON-NLS-1$
  }