Set<Artifact> getResolvedArtifactsFromUnresolvedDependencies(
      List<Dependency> unresolvedDependencies, boolean resolveTransitively)
      throws MojoExecutionException {
    final Set<Artifact> resolvedArtifacts = new HashSet<Artifact>();
    //    Artifact mojoArtifact = this.artifactFactory.createBuildArtifact(project.getGroupId(),
    // project.getArtifactId(), project.getVersion(), "pom");

    /*
     * Resolve each artifact.  This will get all transitive artifacts AND eliminate conflicts.
     */
    final Set<Artifact> unresolvedArtifacts;

    //    for (Dependency d : unresolvedDependencies)
    //      System.out.println("dependency: " + d.toString());

    try {
      unresolvedArtifacts =
          MavenMetadataSource.createArtifacts(
              this.artifactFactory, unresolvedDependencies, null, null, null);
      //      for (Artifact artifact : unresolvedArtifacts) {
      //        System.out.println("unresolved " + artifact.toString());
      //      }

      if (resolveTransitively) {
        ArtifactResolutionResult artifacts =
            artifactResolver.resolveTransitively(
                unresolvedArtifacts,
                project.getArtifact(),
                remoteRepositories,
                localRepository,
                artifactMetadataSource);
        resolvedArtifacts.addAll(artifacts.getArtifacts());
      } else {
        // resolve each artifact individually
        for (Artifact artifact : unresolvedArtifacts) {
          artifactResolver.resolve(artifact, remoteRepositories, localRepository);

          resolvedArtifacts.add(artifact);
        }
      }

    } catch (Exception e) {
      throw new MojoExecutionException("Unable to complete configuring the build settings", e);
    }

    for (Artifact artifact : resolvedArtifacts) {
      System.out.println("matched " + artifact.toString());
    }

    return resolvedArtifacts;
  }
 @SuppressWarnings("unchecked")
 private void prepareArtifacts() {
   try {
     // TODO: do only if artifacts are not resolved
     Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
     Map<String, Artifact> managedVersions = createManagedVersionMap();
     List<ResolutionListener> listeners = new ArrayList<ResolutionListener>();
     ArtifactResolutionResult resolveResult =
         artifactCollector.collect(
             getAllArtifacts(),
             project.getArtifact(),
             managedVersions,
             session.getLocalRepository(),
             project.getRemoteArtifactRepositories(),
             artifactMetadataSource,
             null,
             listeners);
     for (ResolutionNode node : (Set<ResolutionNode>) resolveResult.getArtifactResolutionNodes()) {
       if (!isReactorProject(node.getArtifact())) {
         artifactResolver.resolve(
             node.getArtifact(), node.getRemoteRepositories(), session.getLocalRepository());
         artifacts.add(node.getArtifact());
       } else {
         addProjectReferenceArtifact(node.getArtifact());
       }
     }
     this.artifacts = artifacts;
   } catch (Exception e) {
     getLog().debug("[WarSync] " + e.getMessage(), e);
     getLog().error("[WarSync] " + e.getMessage());
   }
 }
Esempio n. 3
0
  /**
   * Merge WsdlOptions that point to the same file by adding the extraargs to the first option and
   * deleting the second from the options list
   *
   * @param options
   */
  @SuppressWarnings("unchecked")
  private Artifact resolveRemoteWsdlArtifact(List<?> remoteRepos, Artifact artifact)
      throws MojoExecutionException {

    /**
     * First try to find the artifact in the reactor projects of the maven session. So an artifact
     * that is not yet built can be resolved
     */
    List<MavenProject> rProjects = mavenSession.getSortedProjects();
    for (MavenProject rProject : rProjects) {
      if (artifact.getGroupId().equals(rProject.getGroupId())
          && artifact.getArtifactId().equals(rProject.getArtifactId())
          && artifact.getVersion().equals(rProject.getVersion())) {
        Set<Artifact> artifacts = rProject.getArtifacts();
        for (Artifact pArtifact : artifacts) {
          if ("wadl".equals(pArtifact.getType())) {
            return pArtifact;
          }
        }
      }
    }

    /** If this did not work resolve the artifact using the artifactResolver */
    try {
      artifactResolver.resolve(artifact, remoteRepos, localRepository);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException("Error downloading wsdl artifact.", e);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException("Resource can not be found.", e);
    }

    return artifact;
  }
  /**
   * Returns <code>true</code> if the update should be applied.
   *
   * @param artifact The artifact.
   * @param currentVersion The current version of the artifact.
   * @param updateVersion The proposed new version of the artifact.
   * @return <code>true</code> if the update should be applied.
   * @since 1.0-alpha-1
   */
  protected boolean shouldApplyUpdate(
      Artifact artifact, String currentVersion, ArtifactVersion updateVersion) {
    getLog().debug("Proposal is to update from " + currentVersion + " to " + updateVersion);

    if (updateVersion == null) {
      getLog().warn("Not updating version: could not resolve any versions");
      return false;
    }

    artifact.setVersion(updateVersion.toString());
    try {
      resolver.resolveAlways(artifact, remoteArtifactRepositories, localRepository);
    } catch (ArtifactResolutionException e) {
      getLog().warn("Not updating version: could not resolve " + artifact.toString(), e);
      return false;
    } catch (ArtifactNotFoundException e) {
      getLog().warn("Not updating version: could not find " + artifact.toString(), e);
      return false;
    }

    if (currentVersion.equals(updateVersion.toString())) {
      getLog().info("Current version of " + artifact.toString() + " is the latest.");
      return false;
    }
    return true;
  }
  /**
   * Get a resolved Artifact from the coordinates provided
   *
   * @return the artifact, which has been resolved.
   * @throws MojoExecutionException
   */
  protected Artifact getArtifact(
      String groupId, String artifactId, String version, String type, String classifier)
      throws MojoExecutionException {
    Artifact artifact;
    VersionRange vr;

    try {
      vr = VersionRange.createFromVersionSpec(version);
    } catch (InvalidVersionSpecificationException e) {
      vr = VersionRange.createFromVersion(version);
    }

    if (StringUtils.isEmpty(classifier)) {
      artifact =
          factory.createDependencyArtifact(
              groupId, artifactId, vr, type, null, Artifact.SCOPE_COMPILE);
    } else {
      artifact =
          factory.createDependencyArtifact(
              groupId, artifactId, vr, type, classifier, Artifact.SCOPE_COMPILE);
    }
    try {
      resolver.resolve(artifact, remoteRepos, local);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException("Unable to resolve artifact.", e);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException("Unable to find artifact.", e);
    }
    return artifact;
  }
  protected File[] getGwtUserJar() throws MojoExecutionException {
    checkGwtUserVersion();
    Artifact gwtUserArtifact = getArtifact("com.google.gwt", "gwt-user");

    Set<Artifact> artifacts = new HashSet<Artifact>();
    ArtifactResolutionResult result = null;
    try {
      result =
          resolver.resolveTransitively(
              artifacts,
              gwtUserArtifact,
              remoteRepositories,
              localRepository,
              artifactMetadataSource);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException("Failed to resolve artifact", e);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException("Failed to resolve artifact", e);
    }

    Collection<Artifact> resolved = result.getArtifacts();
    int i = 0;
    // FIXME gwt 2.3.0 don't declare dependency on javax.validation, should be fix in next release
    File[] files = new File[resolved.size() + 1 + 2];
    files[i++] = gwtUserArtifact.getFile();
    for (Artifact artifact : resolved) {
      files[i++] = artifact.getFile();
    }

    files[i++] = getArtifact("javax.validation", "validation-api").getFile();
    files[i++] = getArtifact("javax.validation", "validation-api", "sources").getFile();
    return files;
  }
Esempio n. 7
0
  @SuppressWarnings("unchecked")
  private Collection<Artifact> getNonTransitivePlugins(Set<Artifact> projectArtifacts)
      throws MojoExecutionException {
    Collection<Artifact> deps = new LinkedHashSet<Artifact>();

    for (Artifact artifact : projectArtifacts) {
      Artifact pomArtifact =
          artifactFactory.createArtifact(
              artifact.getGroupId(),
              artifact.getArtifactId(),
              artifact.getVersion(),
              artifact.getClassifier(),
              "pom");
      Set<Artifact> result;
      try {
        MavenProject pomProject =
            mavenProjectBuilder.buildFromRepository(
                pomArtifact, remoteRepositories, localRepository);

        Set<Artifact> artifacts = pomProject.createArtifacts(artifactFactory, null, null);
        artifacts = filterOutSystemDependencies(artifacts);
        ArtifactResolutionResult arr =
            resolver.resolveTransitively(
                artifacts,
                pomArtifact,
                localRepository,
                remoteRepositories,
                artifactMetadataSource,
                null);
        result = arr.getArtifacts();
      } catch (Exception e) {
        throw new MojoExecutionException(
            "Failed to resolve non-transitive deps " + e.getMessage(), e);
      }

      LinkedHashSet<Artifact> plugins = new LinkedHashSet<Artifact>();
      plugins.addAll(filtterArtifacts(result, getFilters(null, null, "nexus-plugin", null)));
      plugins.addAll(filtterArtifacts(result, getFilters(null, null, "zip", "bundle")));

      plugins.addAll(getNonTransitivePlugins(plugins));

      if (!plugins.isEmpty()) {
        getLog()
            .debug(
                "Adding non-transitive dependencies for: "
                    + artifact
                    + " -\n"
                    + plugins.toString().replace(',', '\n'));
      }

      deps.addAll(plugins);
    }

    return deps;
  }
Esempio n. 8
0
  protected Artifact resolve(Artifact artifact) throws MojoExecutionException {
    if (!artifact.isResolved()) {
      try {
        resolver.resolve(artifact, remoteRepositories, localRepository);
      } catch (AbstractArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve artifact: " + artifact, e);
      }
    }

    return artifact;
  }
Esempio n. 9
0
  protected void addMvn2CompatResults(
      MavenProject project,
      List<Exception> exceptions,
      List<ResolutionListener> listeners,
      ArtifactRepository localRepository,
      Collection<MavenExecutionResult> executionResults) {
    ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
    resolutionRequest.setArtifactDependencies(project.getDependencyArtifacts());
    resolutionRequest.setArtifact(project.getArtifact());
    resolutionRequest.setManagedVersionMap(project.getManagedVersionMap());
    resolutionRequest.setLocalRepository(localRepository);
    resolutionRequest.setRemoteRepositories(project.getRemoteArtifactRepositories());
    resolutionRequest.setListeners(listeners);

    resolutionRequest.setResolveRoot(false);
    resolutionRequest.setResolveTransitively(true);

    ArtifactResolver resolver = getComponent(ArtifactResolver.class);
    ArtifactResolutionResult result = resolver.resolve(resolutionRequest);

    project.setArtifacts(result.getArtifacts());
    executionResults.add(new MavenExecutionResult(project, exceptions));
  }
  protected Artifact resolve(
      String groupId, String artifactId, String version, String type, String classifier)
      throws MojoExecutionException {
    // return project.getArtifactMap().get( groupId + ":" + artifactId );

    Artifact artifact =
        artifactFactory.createArtifactWithClassifier(
            groupId, artifactId, version, type, classifier);
    try {
      resolver.resolve(artifact, remoteRepositories, localRepository);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException("artifact not found - " + e.getMessage(), e);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException("artifact resolver problem - " + e.getMessage(), e);
    }
    return artifact;
  }
Esempio n. 11
0
  /**
   * Resolves dependencies of a bundle <code>groupId:artifactId:version</code>
   *
   * @param groupId
   * @param artifactId
   * @param version
   */
  @SuppressWarnings("unchecked")
  public ArtifactResolutionResult resolve(
      final String groupId, final String artifactId, final String version) {

    // final Artifact artifact = artifactFactory.createDependencyArtifact(groupId, artifactId,
    // VersionRange.createFromVersion(version), type, "", scope);
    final Artifact pomArtifact = getPomArtifact(groupId, artifactId, version);

    try {
      // load the pom as a MavenProject and get all of the dependencies for the project
      final MavenProject project = loadPomAsProject(projectBuilder, pomArtifact);
      final List dependencies = project.getDependencies();

      // make Artifacts of all the dependencies and the project itself
      final Set<Artifact> dependencyArtifacts =
          MavenMetadataSource.createArtifacts(artifactFactory, dependencies, null, null, null);
      dependencyArtifacts.add(project.getArtifact());

      // create listener for monitoring the resolution process
      final List<RuntimeResolutionListener> listeners = new ArrayList<RuntimeResolutionListener>();
      listeners.add(new RuntimeResolutionListener());

      // resolve all dependencies transitively to obtain a comprehensive list of jars
      final ArtifactResolutionResult result =
          artifactResolver.resolveTransitively(
              dependencyArtifacts,
              pomArtifact,
              Collections.EMPTY_MAP,
              localRepository,
              remoteRepositories,
              metadataSource,
              null,
              listeners);

      if (debug) {
        for (final Object o : result.getArtifactResolutionNodes()) {
          System.out.println(o.toString());
        }
      }

      return result;
    } catch (final Exception e) {
      throw new RuntimeException("Dependency Resolver failed", e);
    }
  }
Esempio n. 12
0
  private Set<Artifact> resolveExecutableDependencies(Artifact executablePomArtifact)
      throws MojoExecutionException {

    Set<Artifact> executableDependencies;
    try {
      MavenProject executableProject =
          this.projectBuilder.buildFromRepository(
              executablePomArtifact, this.remoteRepositories, this.localRepository);

      // get all of the dependencies for the executable project
      List<Artifact> dependencies = CastUtils.cast(executableProject.getDependencies());

      // make Artifacts of all the dependencies
      Set<Artifact> dependencyArtifacts =
          CastUtils.cast(
              MavenMetadataSource.createArtifacts(
                  this.artifactFactory, dependencies, null, null, null));

      // not forgetting the Artifact of the project itself
      dependencyArtifacts.add(executableProject.getArtifact());

      // resolve all dependencies transitively to obtain a comprehensive
      // list of assemblies
      ArtifactResolutionResult result =
          artifactResolver.resolveTransitively(
              dependencyArtifacts,
              executablePomArtifact,
              Collections.EMPTY_MAP,
              this.localRepository,
              this.remoteRepositories,
              metadataSource,
              null,
              Collections.EMPTY_LIST);
      executableDependencies = CastUtils.cast(result.getArtifacts());

    } catch (Exception ex) {
      throw new MojoExecutionException(
          "Encountered problems resolving dependencies of the executable "
              + "in preparation for its execution.",
          ex);
    }

    return executableDependencies;
  }
Esempio n. 13
0
  /**
   * @param isPom <code>true</code> to lookup the <code>maven-model</code> artifact jar, <code>false
   *     </code> to lookup the <code>maven-settings</code> artifact jar.
   * @return the <code>org.apache.maven:maven-model|maven-settings</code> artifact jar file for this
   *     current HelpPlugin pom.
   * @throws MojoExecutionException if any
   * @throws ProjectBuildingException if any
   * @throws ArtifactResolutionException if any
   * @throws ArtifactNotFoundException if any
   */
  private File getArtifactFile(boolean isPom)
      throws MojoExecutionException, ProjectBuildingException, ArtifactResolutionException,
          ArtifactNotFoundException {
    @SuppressWarnings("unchecked")
    List<Dependency> dependencies = getHelpPluginPom().getDependencies();
    for (Dependency depependency : dependencies) {
      if (!(depependency.getGroupId().equals("org.apache.maven"))) {
        continue;
      }

      if (isPom) {
        if (!(depependency.getArtifactId().equals("maven-model"))) {
          continue;
        }
      } else {
        if (!(depependency.getArtifactId().equals("maven-settings"))) {
          continue;
        }
      }

      Artifact mavenArtifact =
          getArtifact(
              depependency.getGroupId()
                  + ":"
                  + depependency.getArtifactId()
                  + ":"
                  + depependency.getVersion());
      resolver.resolveAlways(mavenArtifact, remoteRepositories, localRepository);

      return mavenArtifact.getFile();
    }

    throw new MojoExecutionException(
        "Unable to find the 'org.apache.maven:"
            + (isPom ? "maven-model" : "maven-settings")
            + "' artifact");
  }
  /**
   * Create the transitive classpath.
   *
   * @return The dependent artifacts.
   * @throws MojoExecutionException If the classpath can't be found.
   */
  public Set transitivelyResolvePomDependencies() throws MojoExecutionException {
    // make Artifacts of all the dependencies
    Set dependencyArtifacts;
    try {
      dependencyArtifacts =
          MavenMetadataSource.createArtifacts(artifactFactory, dependencies, null, null, null);
    } catch (InvalidDependencyVersionException e) {
      throw new MojoExecutionException("Invalid dependency", e);
    }

    // not forgetting the Artifact of the project itself
    dependencyArtifacts.add(project.getArtifact());

    List listeners = Collections.EMPTY_LIST;

    // resolve all dependencies transitively to obtain a comprehensive list
    // of jars
    ArtifactResolutionResult result;
    try {
      result =
          artifactResolver.resolveTransitively(
              dependencyArtifacts,
              project.getArtifact(),
              Collections.EMPTY_MAP,
              localRepository,
              remoteRepositories,
              metadataSource,
              null,
              listeners);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException("Unable to resolve Artifact.", e);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException("Unable to resolve Artifact.", e);
    }

    return result.getArtifacts();
  }
  /**
   * Tests if a Filter is installed correctly, also if createSourcesJar is set to true.
   *
   * @throws Exception
   */
  public void testShadeWithFilter() throws Exception {
    ShadeMojo mojo = new ShadeMojo();

    // set createSourcesJar = true
    Field createSourcesJar = ShadeMojo.class.getDeclaredField("createSourcesJar");
    createSourcesJar.setAccessible(true);
    createSourcesJar.set(mojo, Boolean.TRUE);

    // configure artifactFactory for mojo
    ArtifactFactory artifactFactory = (ArtifactFactory) lookup(ArtifactFactory.ROLE);
    Field artifactFactoryField = ShadeMojo.class.getDeclaredField("artifactFactory");
    artifactFactoryField.setAccessible(true);
    artifactFactoryField.set(mojo, artifactFactory);

    // configure artifactResolver (mocked) for mojo
    ArtifactResolver mockArtifactResolver =
        new DefaultArtifactResolver() {

          public void resolve(
              Artifact artifact, List<ArtifactRepository> remoteRepos, ArtifactRepository repo)
              throws ArtifactResolutionException, ArtifactNotFoundException {
            // artifact is resolved
            artifact.setResolved(true);

            // set file
            artifact.setFile(
                new File(
                    artifact.getArtifactId()
                        + "-"
                        + artifact.getVersion()
                        + (artifact.getClassifier() != null ? "-" + artifact.getClassifier() : "")
                        + ".jar"));
          }
        };
    Field artifactResolverField = ShadeMojo.class.getDeclaredField("artifactResolver");
    artifactResolverField.setAccessible(true);
    artifactResolverField.set(mojo, mockArtifactResolver);

    // create and configure MavenProject
    MavenProject project = new MavenProject();
    ArtifactHandler artifactHandler = (ArtifactHandler) lookup(ArtifactHandler.ROLE);
    Artifact artifact =
        new DefaultArtifact(
            "org.apache.myfaces.core",
            "myfaces-impl",
            VersionRange.createFromVersion("2.0.1-SNAPSHOT"),
            "compile",
            "jar",
            null,
            artifactHandler);
    mockArtifactResolver.resolve(artifact, null, null); // setFile and setResolved
    project.setArtifact(artifact);
    Field projectField = ShadeMojo.class.getDeclaredField("project");
    projectField.setAccessible(true);
    projectField.set(mojo, project);

    // create and configure the ArchiveFilter
    ArchiveFilter archiveFilter = new ArchiveFilter();
    Field archiveFilterArtifact = ArchiveFilter.class.getDeclaredField("artifact");
    archiveFilterArtifact.setAccessible(true);
    archiveFilterArtifact.set(archiveFilter, "org.apache.myfaces.core:myfaces-impl");

    // add ArchiveFilter to mojo
    Field filtersField = ShadeMojo.class.getDeclaredField("filters");
    filtersField.setAccessible(true);
    filtersField.set(mojo, new ArchiveFilter[] {archiveFilter});

    // invoke getFilters()
    Method getFilters = ShadeMojo.class.getDeclaredMethod("getFilters", new Class[0]);
    getFilters.setAccessible(true);
    List<Filter> filters = (List<Filter>) getFilters.invoke(mojo);

    // assertions - there must be one filter
    assertEquals(1, filters.size());

    // the filter must be able to filter the binary and the sources jar
    Filter filter = filters.get(0);
    assertTrue(filter.canFilter(new File("myfaces-impl-2.0.1-SNAPSHOT.jar"))); // binary jar
    assertTrue(
        filter.canFilter(new File("myfaces-impl-2.0.1-SNAPSHOT-sources.jar"))); // sources jar
  }
  private void executeServerDeploy(final Wagon wagon) throws MojoExecutionException {

    // alpha|nuclei|beta|electron|gamma|production deployment goes through scpexe
    try {
      if (ensureNoLocalModifications()) {

        @SuppressWarnings("unchecked")
        final List<ArtifactItem> theArtifactItems = getProcessedArtifactItems(stripVersion);

        for (ArtifactItem item : theArtifactItems) {

          final Artifact artifact =
              factory.createArtifactWithClassifier(
                  item.getGroupId(),
                  item.getArtifactId(),
                  item.getVersion(),
                  item.getType(),
                  profile);

          resolver.resolve(artifact, getRemoteRepos(), getLocal());

          final String sesamSite = project.getProperties().getProperty("sesam.site");
          final String destName = null != sesamSite ? sesamSite : project.getBuild().getFinalName();

          // tag the code
          final boolean tagOnDeploy =
              Boolean.parseBoolean(
                  System.getProperty(
                      TAG_ON_DEPLOY, project.getProperties().getProperty("tag.on.deploy")));

          if (tagOnDeploy && !Boolean.getBoolean(DRY_RUN)) {
            tagDeploy();
          }

          // do the upload
          getLog()
              .info(
                  "Uploading "
                      + artifact.getFile().getAbsolutePath()
                      + " to "
                      + wagon.getRepository().getUrl()
                      + '/'
                      + destName
                      + ".war");

          if (!Boolean.getBoolean(DRY_RUN)) {
            wagon.put(artifact.getFile(), destName + ".war");
          }

          // update the version.txt
          getLog().info("Updating " + wagon.getRepository().getUrl() + "/version.txt");

          if (Boolean.getBoolean(DRY_RUN)) {

            final StringWriter sb = new StringWriter();
            final BufferedWriter w = new BufferedWriter(sb);
            updateArtifactEntry(new BufferedReader(new StringReader("")), w);
            w.flush();
            getLog().info("version.txt entry will be \n" + sb.toString());

          } else {

            updateVersionFile(wagon);
          }
        }
      }

    } catch (TransferFailedException ex) {
      getLog().error(ex);
      throw new MojoExecutionException("transfer failed", ex);
    } catch (ResourceDoesNotExistException ex) {
      getLog().error(ex);
      throw new MojoExecutionException("resource does not exist", ex);
    } catch (AuthorizationException ex) {
      getLog().error(ex);
      throw new MojoExecutionException("authorisation exception", ex);
    } catch (ArtifactNotFoundException ex) {
      getLog().error(ex);
      throw new MojoExecutionException("artifact not found", ex);
    } catch (ArtifactResolutionException ex) {
      getLog().error(ex);
      throw new MojoExecutionException("artifact resolution exception", ex);
    } catch (ScmException ex) {
      getLog().error(ex);
      throw new MojoExecutionException("scm exception", ex);
    } catch (ComponentLookupException ex) {
      getLog().error(ex);
      throw new MojoExecutionException("failed to lookup ScmManager", ex);
    } catch (IOException ex) {
      getLog().error(ex);
      throw new MojoExecutionException("IOException", ex);
    }
  }
  @Override
  public void execute(final EnforcerRuleHelper helper) throws EnforcerRuleException {
    final MavenProject project;
    try {
      project = (MavenProject) helper.evaluate("${project}");
    } catch (ExpressionEvaluationException e) {
      throw new EnforcerRuleException("Failed to access ${project} variable", e);
    }
    final String type = project.getArtifact().getType();
    if (!AbstractEnforcerRule.JAR_ARTIFACT_TYPE.equals(type)) {
      helper
          .getLog()
          .debug("Skipping non " + AbstractEnforcerRule.JAR_ARTIFACT_TYPE + " artifact.");
      return;
    }

    final Artifact previousArtifact;
    final Artifact currentArtifact = project.getArtifact();
    validateArtifact(currentArtifact);
    final Version current = Version.parse(currentArtifact.getVersion());
    final File currentJar = currentArtifact.getFile();
    try {
      final ArtifactRepository localRepository =
          (ArtifactRepository) helper.evaluate("${localRepository}");
      final String version;
      if (this.previousVersion != null) {
        version = this.previousVersion;

        helper.getLog().info("Version specified as <" + version + ">");
      } else {
        final ArtifactMetadataSource artifactMetadataSource =
            (ArtifactMetadataSource) helper.getComponent(ArtifactMetadataSource.class);
        final List<ArtifactVersion> availableVersions =
            getAvailableReleasedVersions(artifactMetadataSource, project, localRepository);
        final List<ArtifactVersion> availablePreviousVersions =
            filterNonPreviousVersions(availableVersions, current);

        if (availablePreviousVersions.isEmpty()) {
          helper
              .getLog()
              .warn("No previously released version. Backward compatibility check not performed.");

          return;
        }

        version = availablePreviousVersions.iterator().next().toString();

        helper
            .getLog()
            .info(
                "Version deduced as <"
                    + version
                    + "> (among all availables: "
                    + availablePreviousVersions
                    + ")");
      }

      final ArtifactFactory artifactFactory =
          (ArtifactFactory) helper.getComponent(ArtifactFactory.class);
      previousArtifact =
          artifactFactory.createArtifact(
              project.getGroupId(), project.getArtifactId(), version, null, type);
      final ArtifactResolver resolver =
          (ArtifactResolver) helper.getComponent(ArtifactResolver.class);
      resolver.resolve(previousArtifact, project.getRemoteArtifactRepositories(), localRepository);

      validateArtifact(previousArtifact);
    } catch (Exception e) {
      helper.getLog().warn("Exception while accessing artifacts; skipping check.", e);
      return;
    }

    final Version previous = Version.parse(previousArtifact.getVersion());
    final File previousJar = previousArtifact.getFile();

    helper.getLog().info("Using <" + previousJar + "> as previous JAR");
    helper.getLog().info("Using <" + currentJar + "> as current JAR");

    try {
      final Comparer comparer =
          new Comparer(
              previousJar,
              currentJar,
              extractFilters(this.includes),
              extractFilters(this.excludes));
      final Delta delta = comparer.diff();

      enforce(helper, delta, previous, current);
    } catch (IOException e) {
      throw new EnforcerRuleException("Exception while checking compatibility: " + e.toString(), e);
    }
  }
  public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
      getLog().info("skip execution");
      return;
    }
    // project.addAttachedArtifact(  );
    File warExecFile = new File(buildDirectory, finalName);
    if (warExecFile.exists()) {
      warExecFile.delete();
    }

    File execWarJar = new File(buildDirectory, finalName);

    FileOutputStream execWarJarOutputStream = null;
    ArchiveOutputStream os = null;
    File tmpPropertiesFile = null;
    File tmpManifestFile = null;
    FileOutputStream tmpPropertiesFileOutputStream = null;
    PrintWriter tmpManifestWriter = null;

    try {

      tmpPropertiesFile = new File(buildDirectory, "war-exec.properties");
      if (tmpPropertiesFile.exists()) {
        tmpPropertiesFile.delete();
      }
      tmpPropertiesFile.getParentFile().mkdirs();

      tmpManifestFile = new File(buildDirectory, "war-exec.manifest");
      if (tmpManifestFile.exists()) {
        tmpManifestFile.delete();
      }
      tmpPropertiesFileOutputStream = new FileOutputStream(tmpPropertiesFile);
      execWarJar.getParentFile().mkdirs();
      execWarJar.createNewFile();
      execWarJarOutputStream = new FileOutputStream(execWarJar);

      tmpManifestWriter = new PrintWriter(tmpManifestFile);

      // store :
      // * wars in the root: foo.war
      // * tomcat jars
      // * file tomcat.standalone.properties with possible values :
      //   * useServerXml=true/false to use directly the one provided
      //   * enableNaming=true/false
      //   * wars=foo.war|contextpath;bar.war  ( |contextpath is optionnal if empty use the war name
      // )
      //   * accessLogValveFormat=
      //   * connectorhttpProtocol: HTTP/1.1 or org.apache.coyote.http11.Http11NioProtocol
      // * optionnal: conf/ with usual tomcat configuration files
      // * MANIFEST with Main-Class

      Properties properties = new Properties();

      properties.put(
          Tomcat7Runner.ARCHIVE_GENERATION_TIMESTAMP_KEY,
          Long.toString(System.currentTimeMillis()));
      properties.put(Tomcat7Runner.ENABLE_NAMING_KEY, Boolean.toString(enableNaming));
      properties.put(Tomcat7Runner.ACCESS_LOG_VALVE_FORMAT_KEY, accessLogValveFormat);
      properties.put(Tomcat7Runner.HTTP_PROTOCOL_KEY, connectorHttpProtocol);

      os =
          new ArchiveStreamFactory()
              .createArchiveOutputStream(ArchiveStreamFactory.JAR, execWarJarOutputStream);

      if ("war".equals(project.getPackaging())) {

        os.putArchiveEntry(new JarArchiveEntry(StringUtils.removeStart(path, "/") + ".war"));
        IOUtils.copy(new FileInputStream(projectArtifact.getFile()), os);
        os.closeArchiveEntry();

        properties.put(Tomcat7Runner.WARS_KEY, StringUtils.removeStart(path, "/") + ".war|" + path);
      } else if (warRunDependencies != null && !warRunDependencies.isEmpty()) {
        for (WarRunDependency warRunDependency : warRunDependencies) {
          if (warRunDependency.dependency != null) {
            Dependency dependency = warRunDependency.dependency;
            Artifact artifact =
                artifactFactory.createArtifactWithClassifier(
                    dependency.getGroupId(),
                    dependency.getArtifactId(),
                    dependency.getVersion(),
                    dependency.getType(),
                    dependency.getClassifier());

            artifactResolver.resolve(artifact, this.remoteRepos, this.local);

            File warFileToBundle = new File(resolvePluginWorkDir(), artifact.getFile().getName());
            FileUtils.copyFile(artifact.getFile(), warFileToBundle);

            if (warRunDependency.contextXml != null) {
              warFileToBundle = addContextXmlToWar(warRunDependency.contextXml, warFileToBundle);
            }
            final String warFileName = artifact.getFile().getName();
            os.putArchiveEntry(new JarArchiveEntry(warFileName));
            IOUtils.copy(new FileInputStream(warFileToBundle), os);
            os.closeArchiveEntry();
            String propertyWarValue = properties.getProperty(Tomcat7Runner.WARS_KEY);
            String contextPath =
                StringUtils.isEmpty(warRunDependency.contextPath)
                    ? "/"
                    : warRunDependency.contextPath;
            if (propertyWarValue != null) {
              properties.put(
                  Tomcat7Runner.WARS_KEY, propertyWarValue + ";" + warFileName + "|" + contextPath);
            } else {
              properties.put(Tomcat7Runner.WARS_KEY, warFileName + "|" + contextPath);
            }
          }
        }
      }

      if (serverXml != null && serverXml.exists()) {
        os.putArchiveEntry(new JarArchiveEntry("conf/server.xml"));
        IOUtils.copy(new FileInputStream(serverXml), os);
        os.closeArchiveEntry();
        properties.put(Tomcat7Runner.USE_SERVER_XML_KEY, Boolean.TRUE.toString());
      } else {
        properties.put(Tomcat7Runner.USE_SERVER_XML_KEY, Boolean.FALSE.toString());
      }

      os.putArchiveEntry(new JarArchiveEntry("conf/web.xml"));
      IOUtils.copy(getClass().getResourceAsStream("/conf/web.xml"), os);
      os.closeArchiveEntry();

      properties.store(tmpPropertiesFileOutputStream, "created by Apache Tomcat Maven plugin");

      tmpPropertiesFileOutputStream.flush();
      tmpPropertiesFileOutputStream.close();

      os.putArchiveEntry(new JarArchiveEntry(Tomcat7RunnerCli.STAND_ALONE_PROPERTIES_FILENAME));
      IOUtils.copy(new FileInputStream(tmpPropertiesFile), os);
      os.closeArchiveEntry();

      // add tomcat classes
      for (Artifact pluginArtifact : pluginArtifacts) {
        if (StringUtils.equals("org.apache.tomcat", pluginArtifact.getGroupId())
            || StringUtils.equals("org.apache.tomcat.embed", pluginArtifact.getGroupId())
            || StringUtils.equals("org.eclipse.jdt.core.compiler", pluginArtifact.getGroupId())
            || StringUtils.equals("commons-cli", pluginArtifact.getArtifactId())
            || StringUtils.equals("tomcat7-war-runner", pluginArtifact.getArtifactId())) {
          JarFile jarFile = new JarFile(pluginArtifact.getFile());
          extractJarToArchive(jarFile, os);
        }
      }

      // add extra dependencies
      if (extraDependencies != null && !extraDependencies.isEmpty()) {
        for (Dependency dependency : extraDependencies) {
          // String groupId, String artifactId, String version, String scope, String type
          Artifact artifact =
              artifactFactory.createArtifact(
                  dependency.getGroupId(),
                  dependency.getArtifactId(),
                  dependency.getVersion(),
                  dependency.getScope(),
                  dependency.getType());

          artifactResolver.resolve(artifact, this.remoteRepos, this.local);
          JarFile jarFile = new JarFile(artifact.getFile());
          extractJarToArchive(jarFile, os);
        }
      }

      Manifest manifest = new Manifest();

      Manifest.Attribute mainClassAtt = new Manifest.Attribute();
      mainClassAtt.setName("Main-Class");
      mainClassAtt.setValue(mainClass);
      manifest.addConfiguredAttribute(mainClassAtt);

      manifest.write(tmpManifestWriter);
      tmpManifestWriter.flush();
      tmpManifestWriter.close();

      os.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
      IOUtils.copy(new FileInputStream(tmpManifestFile), os);
      os.closeArchiveEntry();

      if (attachArtifact) {
        // MavenProject project, String artifactType, String artifactClassifier, File artifactFile
        projectHelper.attachArtifact(
            project, attachArtifactClassifierType, attachArtifactClassifier, execWarJar);
      }

      if (extraResources != null) {
        for (ExtraResource extraResource : extraResources) {

          DirectoryScanner directoryScanner = new DirectoryScanner();
          directoryScanner.setBasedir(extraResource.getDirectory());
          directoryScanner.addDefaultExcludes();
          directoryScanner.setExcludes(toStringArray(extraResource.getExcludes()));
          directoryScanner.setIncludes(toStringArray(extraResource.getIncludes()));
          directoryScanner.scan();
          for (String includeFile : directoryScanner.getIncludedFiles()) {
            getLog().debug("include file:" + includeFile);
            os.putArchiveEntry(new JarArchiveEntry(includeFile));
            IOUtils.copy(
                new FileInputStream(new File(extraResource.getDirectory(), includeFile)), os);
            os.closeArchiveEntry();
          }
        }
      }

      if (tomcatConfigurationFilesDirectory != null && tomcatConfigurationFilesDirectory.exists()) {
        // Because its the tomcat default dir for configs
        String aConfigOutputDir = "conf/";
        copyDirectoryContentIntoArchive(tomcatConfigurationFilesDirectory, aConfigOutputDir, os);
      }

    } catch (ManifestException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArchiveException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } finally {
      IOUtils.closeQuietly(os);
      IOUtils.closeQuietly(tmpManifestWriter);
      IOUtils.closeQuietly(execWarJarOutputStream);
      IOUtils.closeQuietly(tmpPropertiesFileOutputStream);
    }
  }