@Override
  protected List<File> getDependencies() {
    ArrayList<File> dependencies = new ArrayList<File>();

    @SuppressWarnings("unchecked")
    final Iterator<Artifact> it = project.getArtifacts().iterator();
    while (it.hasNext()) {
      final Artifact declared = it.next();
      this.log.debug("Checking artifact " + declared);
      if (this.isJavaArtifact(declared)) {
        if (Artifact.SCOPE_COMPILE.equals(declared.getScope())
            || Artifact.SCOPE_RUNTIME.equals(declared.getScope())
            || Artifact.SCOPE_PROVIDED.equals(declared.getScope())
            || Artifact.SCOPE_SYSTEM.equals(declared.getScope())) {
          this.log.debug("Resolving artifact " + declared);
          if (declared.getFile() != null) {
            dependencies.add(declared.getFile());
          } else {
            this.log.debug("Unable to resolve artifact " + declared);
          }
        } else {
          this.log.debug(
              "Artifact "
                  + declared
                  + " has not scope compile or runtime, but "
                  + declared.getScope());
        }
      } else {
        this.log.debug(
            "Artifact " + declared + " is not a java artifact, type is " + declared.getType());
      }
    }

    return dependencies;
  }
Esempio n. 2
0
  /**
   * @param artifactObj not null
   * @return the POM for the given artifact.
   * @throws MojoExecutionException if the artifact has a system scope.
   * @throws ProjectBuildingException when building pom.
   */
  private MavenProject getMavenProject(Artifact artifactObj)
      throws MojoExecutionException, ProjectBuildingException {
    if (Artifact.SCOPE_SYSTEM.equals(artifactObj.getScope())) {
      throw new MojoExecutionException("System artifact is not be handled.");
    }

    Artifact copyArtifact = ArtifactUtils.copyArtifact(artifactObj);
    if (!"pom".equals(copyArtifact.getType())) {
      copyArtifact =
          artifactFactory.createProjectArtifact(
              copyArtifact.getGroupId(), copyArtifact.getArtifactId(),
              copyArtifact.getVersion(), copyArtifact.getScope());
    }

    return mavenProjectBuilder.buildFromRepository(
        copyArtifact, remoteRepositories, localRepository);
  }
    public boolean isReferenceFromEar(IClasspathEntryDescriptor descriptor) {

      IClasspathEntry entry = descriptor.getClasspathEntry();
      String scope = descriptor.getScope();

      // these dependencies aren't added to the manifest cp
      // retain optional dependencies here, they might be used just to express the
      // dependency to be used in the manifest
      if (Artifact.SCOPE_PROVIDED.equals(scope)
          || Artifact.SCOPE_TEST.equals(scope)
          || Artifact.SCOPE_SYSTEM.equals(scope)) {
        return false;
      }

      // calculate in regard to includes/excludes whether this jar is
      // to be packaged into  WEB-INF/lib
      String jarFileName = "WEB-INF/lib/" + entry.getPath().lastSegment();
      return isExcludedFromWebInfLib(jarFileName);
    }
Esempio n. 4
0
  private Artifact XcreateArtifact(
      String groupId,
      String artifactId,
      VersionRange versionRange,
      String type,
      String classifier,
      String scope,
      String inheritedScope,
      boolean optional) {
    String desiredScope = Artifact.SCOPE_RUNTIME;

    if (inheritedScope == null) {
      desiredScope = scope;
    } else if (Artifact.SCOPE_TEST.equals(scope) || Artifact.SCOPE_PROVIDED.equals(scope)) {
      return null;
    } else if (Artifact.SCOPE_COMPILE.equals(scope)
        && Artifact.SCOPE_COMPILE.equals(inheritedScope)) {
      // added to retain compile artifactScope. Remove if you want compile inherited as runtime
      desiredScope = Artifact.SCOPE_COMPILE;
    }

    if (Artifact.SCOPE_TEST.equals(inheritedScope)) {
      desiredScope = Artifact.SCOPE_TEST;
    }

    if (Artifact.SCOPE_PROVIDED.equals(inheritedScope)) {
      desiredScope = Artifact.SCOPE_PROVIDED;
    }

    if (Artifact.SCOPE_SYSTEM.equals(scope)) {
      // system scopes come through unchanged...
      desiredScope = Artifact.SCOPE_SYSTEM;
    }

    ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(type);

    return new DefaultArtifact(
        groupId, artifactId, versionRange, desiredScope, type, classifier, handler, optional);
  }
Esempio n. 5
0
  // DefaultProjectBuilder
  public Artifact createDependencyArtifact(Dependency d) {
    if (d.getVersion() == null) {
      return null;
    }

    VersionRange versionRange;
    try {
      versionRange = VersionRange.createFromVersionSpec(d.getVersion());
    } catch (InvalidVersionSpecificationException e) {
      return null;
    }

    Artifact artifact =
        XcreateDependencyArtifact(
            d.getGroupId(),
            d.getArtifactId(),
            versionRange,
            d.getType(),
            d.getClassifier(),
            d.getScope(),
            d.isOptional());

    if (Artifact.SCOPE_SYSTEM.equals(d.getScope()) && d.getSystemPath() != null) {
      artifact.setFile(new File(d.getSystemPath()));
    }

    if (!d.getExclusions().isEmpty()) {
      List<String> exclusions = new ArrayList<>();

      for (Exclusion exclusion : d.getExclusions()) {
        exclusions.add(exclusion.getGroupId() + ':' + exclusion.getArtifactId());
      }

      artifact.setDependencyFilter(new ExcludesArtifactFilter(exclusions));
    }

    return artifact;
  }
  public void configureClasspath(
      IProject project,
      MavenProject mavenProject,
      IClasspathDescriptor classpath,
      IProgressMonitor monitor)
      throws CoreException {

    // Improve skinny war support by generating the manifest classpath
    // similar to mvn eclipse:eclipse
    // http://maven.apache.org/plugins/maven-war-plugin/examples/skinny-wars.html
    WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
    WarPackagingOptions opts = new WarPackagingOptions(config);

    StringBuilder manifestCp = new StringBuilder();

    /*
     * Need to take care of three separate cases
     *
     * 1. remove any project dependencies (they are represented as J2EE module dependencies)
     * 2. add non-dependency attribute for entries originated by artifacts with
     *    runtime, system, test scopes or optional dependencies (not sure about the last one)
     * 3. make sure all dependency JAR files have unique file names, i.e. artifactId/version collisions
     */

    Set<String> dups = new LinkedHashSet<String>();
    Set<String> names = new HashSet<String>();

    // first pass removes projects, adds non-dependency attribute and collects colliding filenames
    Iterator<IClasspathEntryDescriptor> iter = classpath.getEntryDescriptors().iterator();
    while (iter.hasNext()) {
      IClasspathEntryDescriptor descriptor = iter.next();
      IClasspathEntry entry = descriptor.getClasspathEntry();
      String scope = descriptor.getScope();
      String key =
          ArtifactUtils.versionlessKey(descriptor.getGroupId(), descriptor.getArtifactId());
      Artifact artifact = mavenProject.getArtifactMap().get(key);
      String extension = artifact.getArtifactHandler().getExtension();

      if (IClasspathEntry.CPE_PROJECT == entry.getEntryKind()
          && Artifact.SCOPE_COMPILE.equals(scope)) {
        // get deployed name for project dependencies
        // TODO can this be done somehow more elegantly?
        IProject p =
            (IProject) ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath());

        IVirtualComponent component = ComponentCore.createComponent(p);

        boolean usedInEar = opts.isReferenceFromEar(component, extension);
        if (opts.isSkinnyWar() && usedInEar) {
          if (manifestCp.length() > 0) {
            manifestCp.append(" ");
          }
          // MNGECLIPSE-2393 prepend ManifestClasspath prefix
          if (config.getManifestClasspathPrefix() != null
              && !JEEPackaging.isJEEPackaging(artifact.getType())) {
            manifestCp.append(config.getManifestClasspathPrefix());
          }

          manifestCp.append(component.getDeployedName()).append(".").append(extension);
        }

        if (!descriptor.isOptionalDependency() || usedInEar) {
          // remove mandatory project dependency from classpath
          iter.remove();
          continue;
        } // else : optional dependency not used in ear -> need to trick ClasspathAttribute with
          // NONDEPENDENCY_ATTRIBUTE
      }

      if (opts.isSkinnyWar() && opts.isReferenceFromEar(descriptor)) {

        if (manifestCp.length() > 0) {
          manifestCp.append(" ");
        }
        if (config.getManifestClasspathPrefix() != null
            && !JEEPackaging.isJEEPackaging(artifact.getType())) {
          manifestCp.append(config.getManifestClasspathPrefix());
        }
        manifestCp.append(entry.getPath().lastSegment());

        // ear references aren't kept in the Maven Dependencies
        iter.remove();
        continue;
      }

      // add non-dependency attribute
      // Check the scope & set WTP non-dependency as appropriate
      // Optional artifact shouldn't be deployed
      if (Artifact.SCOPE_PROVIDED.equals(scope)
          || Artifact.SCOPE_TEST.equals(scope)
          || Artifact.SCOPE_SYSTEM.equals(scope)
          || descriptor.isOptionalDependency()) {
        descriptor.addClasspathAttribute(NONDEPENDENCY_ATTRIBUTE);
      }

      // collect duplicate file names
      if (!names.add(entry.getPath().lastSegment())) {
        dups.add(entry.getPath().lastSegment());
      }
    }

    String targetDir = mavenProject.getBuild().getDirectory();

    // second pass disambiguates colliding entry file names
    iter = classpath.getEntryDescriptors().iterator();
    while (iter.hasNext()) {
      IClasspathEntryDescriptor descriptor = iter.next();
      IClasspathEntry entry = descriptor.getClasspathEntry();

      if (dups.contains(entry.getPath().lastSegment())) {
        File src = new File(entry.getPath().toOSString());
        String groupId = descriptor.getGroupId();
        File dst = new File(targetDir, groupId + "-" + entry.getPath().lastSegment());
        try {
          if (src.canRead()) {
            if (isDifferent(src, dst)) { // uses lastModified
              FileUtils.copyFile(src, dst);
              dst.setLastModified(src.lastModified());
            }
            descriptor.setClasspathEntry(
                JavaCore.newLibraryEntry(
                    Path.fromOSString(dst.getCanonicalPath()), //
                    entry.getSourceAttachmentPath(), //
                    entry.getSourceAttachmentRootPath(), //
                    entry.getAccessRules(), //
                    entry.getExtraAttributes(), //
                    entry.isExported()));
          }
        } catch (IOException ex) {
          MavenLogger.log("File copy failed", ex);
        }
      }
    }

    if (opts.isSkinnyWar()) {

      // writing the manifest only works when the project has been properly created
      // placing this check on the top of the method broke 2 other tests
      // thats why its placed here now.
      if (ComponentCore.createComponent(project) == null) {
        return;
      }

      // write manifest, using internal API - seems ok for 3.4/3.5, though
      ArchiveManifest mf = J2EEProjectUtilities.readManifest(project);
      if (mf == null) {
        mf = new ArchiveManifestImpl();
      }
      mf.addVersionIfNecessary();
      mf.setClassPath(manifestCp.toString());

      try {
        J2EEProjectUtilities.writeManifest(project, mf);
      } catch (Exception ex) {
        MavenLogger.log("Could not write web module manifest file", ex);
      }
    }
  }
  /**
   * Resolve project dependencies. Manual resolution is needed in order to avoid resoltion of
   * multiproject artifacts (if projects will be linked each other an installed jar is not needed)
   * and to avoid a failure when a jar is missing.
   *
   * @throws MojoExecutionException if dependencies can't be resolved
   * @return resoved IDE dependencies, with attached jars for non-reactor dependencies
   */
  protected IdeDependency[] doDependencyResolution() throws MojoExecutionException {
    MavenProject project = getProject();
    ArtifactRepository localRepo = getLocalRepository();

    List dependencies = getProject().getDependencies();

    // Collect the list of resolved IdeDependencies.
    List dependencyList = new ArrayList();

    if (dependencies != null) {
      Map managedVersions =
          createManagedVersionMap(
              getArtifactFactory(), project.getId(), project.getDependencyManagement());

      ArtifactResolutionResult artifactResolutionResult = null;

      try {

        List listeners = new ArrayList();

        if (logger.isDebugEnabled()) {
          listeners.add(new DebugResolutionListener(logger));
        }

        listeners.add(new WarningResolutionListener(logger));

        artifactResolutionResult =
            artifactCollector.collect(
                getProjectArtifacts(),
                project.getArtifact(),
                managedVersions,
                localRepo,
                project.getRemoteArtifactRepositories(),
                getArtifactMetadataSource(),
                null,
                listeners);
      } catch (ArtifactResolutionException e) {
        getLog().debug(e.getMessage(), e);
        getLog()
            .error(
                Messages.getString(
                    "artifactresolution",
                    new Object[] { // $NON-NLS-1$
                      e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage()
                    }));

        // if we are here artifactResolutionResult is null, create a project without dependencies
        // but don't fail
        // (this could be a reactor projects, we don't want to fail everything)
        return new IdeDependency[0];
      }

      // keep track of added reactor projects in order to avoid duplicates
      Set emittedReactorProjectId = new HashSet();

      for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator();
          i.hasNext(); ) {
        ResolutionNode node = (ResolutionNode) i.next();
        Artifact art = node.getArtifact();
        boolean isReactorProject = getUseProjectReferences() && isAvailableAsAReactorProject(art);

        // don't resolve jars for reactor projects
        if (!isReactorProject) {
          try {
            artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository);
          } catch (ArtifactNotFoundException e) {
            getLog().debug(e.getMessage(), e);
            getLog()
                .warn(
                    Messages.getString(
                        "artifactdownload",
                        new Object[] { // $NON-NLS-1$
                          e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage()
                        }));
          } catch (ArtifactResolutionException e) {
            getLog().debug(e.getMessage(), e);
            getLog()
                .warn(
                    Messages.getString(
                        "artifactresolution",
                        new Object[] { // $NON-NLS-1$
                          e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage()
                        }));
          }
        }

        if (!isReactorProject
            || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId())) {

          IdeDependency dep =
              new IdeDependency(
                  art.getGroupId(),
                  art.getArtifactId(),
                  art.getVersion(),
                  isReactorProject,
                  Artifact.SCOPE_TEST.equals(art.getScope()),
                  Artifact.SCOPE_SYSTEM.equals(art.getScope()),
                  Artifact.SCOPE_PROVIDED.equals(art.getScope()),
                  art.getArtifactHandler().isAddedToClasspath(),
                  art.getFile(),
                  art.getType());

          dependencyList.add(dep);
        }
      }

      // @todo a final report with the list of missingArtifacts?

    }

    IdeDependency[] deps =
        (IdeDependency[]) dependencyList.toArray(new IdeDependency[dependencyList.size()]);

    return deps;
  }
  private void resolveOld(
      Artifact artifact,
      List<ArtifactRepository> remoteRepositories,
      RepositorySystemSession session)
      throws ArtifactResolutionException, ArtifactNotFoundException {
    if (artifact == null) {
      return;
    }

    if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) {
      File systemFile = artifact.getFile();

      if (systemFile == null) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " has no file attached", artifact);
      }

      if (!systemFile.exists()) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " not found in path: " + systemFile, artifact);
      }

      if (!systemFile.isFile()) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " is not a file: " + systemFile, artifact);
      }

      artifact.setResolved(true);

      return;
    }

    if (!artifact.isResolved()) {
      ArtifactResult result;

      try {
        ArtifactRequest artifactRequest = new ArtifactRequest();
        artifactRequest.setArtifact(RepositoryUtils.toArtifact(artifact));
        artifactRequest.setRepositories(RepositoryUtils.toRepos(remoteRepositories));

        // Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved
        // or not
        LocalRepositoryManager lrm = session.getLocalRepositoryManager();
        String path = lrm.getPathForLocalArtifact(artifactRequest.getArtifact());
        artifact.setFile(new File(lrm.getRepository().getBasedir(), path));

        result = repoSystem.resolveArtifact(session, artifactRequest);
      } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) {
        if (e.getCause() instanceof org.eclipse.aether.transfer.ArtifactNotFoundException) {
          throw new ArtifactNotFoundException(
              e.getMessage(),
              artifact.getGroupId(),
              artifact.getArtifactId(),
              artifact.getVersion(),
              artifact.getType(),
              artifact.getClassifier(),
              remoteRepositories,
              artifact.getDownloadUrl(),
              artifact.getDependencyTrail(),
              e);
        } else {
          throw new ArtifactResolutionException(e.getMessage(), artifact, remoteRepositories, e);
        }
      }

      artifact.selectVersion(result.getArtifact().getVersion());
      artifact.setFile(result.getArtifact().getFile());
      artifact.setResolved(true);

      if (artifact.isSnapshot()) {
        Matcher matcher = Artifact.VERSION_FILE_PATTERN.matcher(artifact.getVersion());
        if (matcher.matches()) {
          Snapshot snapshot = new Snapshot();
          snapshot.setTimestamp(matcher.group(2));
          try {
            snapshot.setBuildNumber(Integer.parseInt(matcher.group(3)));
            artifact.addMetadata(new SnapshotArtifactRepositoryMetadata(artifact, snapshot));
          } catch (NumberFormatException e) {
            logger.warn(
                "Invalid artifact version " + artifact.getVersion() + ": " + e.getMessage());
          }
        }
      }
    }
  }