Exemplo n.º 1
0
 public static String getCamelVersion(IProject project) {
   IPath pomPathValue =
       project.getProject().getRawLocation() != null
           ? project.getProject().getRawLocation().append("pom.xml")
           : ResourcesPlugin.getWorkspace()
               .getRoot()
               .getLocation()
               .append(project.getFullPath().append("pom.xml"));
   String pomPath = pomPathValue.toOSString();
   final File pomFile = new File(pomPath);
   try {
     final org.apache.maven.model.Model model = MavenPlugin.getMaven().readModel(pomFile);
     List<org.apache.maven.model.Dependency> deps = model.getDependencies();
     for (Iterator<org.apache.maven.model.Dependency> iterator = deps.iterator();
         iterator.hasNext(); ) {
       org.apache.maven.model.Dependency dependency = iterator.next();
       if (dependency.getArtifactId().equals("camel-core")) {
         return dependency.getVersion();
       }
     }
   } catch (CoreException e) {
     // not found, go with default
   }
   return org.fusesource.ide.camel.editor.Activator.getDefault().getCamelVersion();
 }
Exemplo n.º 2
0
  public List<String> getDependencies() {
    List<Dependency> deps = pom.getDependencies();
    if (deps == null) return null;

    final List<String> dependencies = new ArrayList<String>();
    for (Dependency dep : deps) {
      if (!dep.isOptional()) {
        String coords =
            dep.getGroupId()
                + ":"
                + dep.getArtifactId()
                + ":"
                + dep.getVersion()
                + (dep.getClassifier() != null && !dep.getClassifier().isEmpty()
                    ? ":" + dep.getClassifier()
                    : "");
        List<Exclusion> exclusions = dep.getExclusions();
        if (exclusions != null && !exclusions.isEmpty()) {
          StringBuilder sb = new StringBuilder();
          sb.append('(');
          for (Exclusion ex : exclusions)
            sb.append(ex.getGroupId()).append(':').append(ex.getArtifactId()).append(',');
          sb.delete(sb.length() - 1, sb.length());
          sb.append(')');
          coords += sb.toString();
        }
        dependencies.add(coords);
      }
    }
    return dependencies;
  }
  private List<String> alterModel(MavenProject project, String newVersion) {
    Model originalModel = project.getOriginalModel();
    originalModel.setVersion(newVersion);

    List<String> errors = new ArrayList<String>();

    String searchingFrom = project.getArtifactId();
    MavenProject parent = project.getParent();
    if (parent != null && isSnapshot(parent.getVersion())) {
      try {
        ReleasableModule parentBeingReleased =
            reactor.find(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
        originalModel.getParent().setVersion(parentBeingReleased.getVersionToDependOn());
        log.debug(
            " Parent "
                + parentBeingReleased.getArtifactId()
                + " rewritten to version "
                + parentBeingReleased.getVersionToDependOn());
      } catch (UnresolvedSnapshotDependencyException e) {
        errors.add("The parent of " + searchingFrom + " is " + e.artifactId + " " + e.version);
      }
    }
    for (Dependency dependency : originalModel.getDependencies()) {
      String version = dependency.getVersion();
      if (isSnapshot(version)) {
        try {
          ReleasableModule dependencyBeingReleased =
              reactor.find(dependency.getGroupId(), dependency.getArtifactId(), version);
          dependency.setVersion(dependencyBeingReleased.getVersionToDependOn());
          log.debug(
              " Dependency on "
                  + dependencyBeingReleased.getArtifactId()
                  + " rewritten to version "
                  + dependencyBeingReleased.getVersionToDependOn());
        } catch (UnresolvedSnapshotDependencyException e) {
          errors.add(searchingFrom + " references dependency " + e.artifactId + " " + e.version);
        }
      } else
        log.debug(
            " Dependency on "
                + dependency.getArtifactId()
                + " kept at version "
                + dependency.getVersion());
    }
    for (Plugin plugin : project.getModel().getBuild().getPlugins()) {
      String version = plugin.getVersion();
      if (isSnapshot(version)) {
        if (!isMultiModuleReleasePlugin(plugin)) {
          errors.add(
              searchingFrom + " references plugin " + plugin.getArtifactId() + " " + version);
        }
      }
    }
    return errors;
  }
Exemplo n.º 4
0
  public static void updateMavenDependencies(
      final List<Dependency> dependencies, final IProject project) throws CoreException {
    final IFile pomIFile = project.getProject().getFile("pom.xml");
    final File pomFile = new File(pomIFile.getLocationURI());
    final org.apache.maven.model.Model pom = MavenPlugin.getMaven().readModel(pomFile);

    // Check if dependency already in the pom
    final List<Dependency> missingDependencies = new ArrayList<>();
    for (final Dependency dependency : dependencies) {
      boolean found = false;
      for (final org.apache.maven.model.Dependency pomDependency : pom.getDependencies()) {
        if (pomDependency.getGroupId().equalsIgnoreCase(dependency.getGroupId())
            && pomDependency.getArtifactId().equalsIgnoreCase(dependency.getArtifactId())) {
          // check for correct version
          if (!pomDependency.getVersion().equalsIgnoreCase(dependency.getVersion())) {
            pomDependency.setVersion(dependency.getVersion());
          }
          found = true;
          break;
        }
      }
      if (!found) {
        missingDependencies.add(dependency);
      }
    }

    for (final Dependency dependency : missingDependencies) {
      final org.apache.maven.model.Dependency pomDependency =
          new org.apache.maven.model.Dependency();
      pomDependency.setGroupId(dependency.getGroupId());
      pomDependency.setArtifactId(dependency.getArtifactId());
      pomDependency.setVersion(dependency.getVersion());
      pom.addDependency(pomDependency);
    }

    if (!missingDependencies.isEmpty()) {
      try (final OutputStream stream = new BufferedOutputStream(new FileOutputStream(pomFile))) {
        MavenPlugin.getMaven().writeModel(pom, stream);
        pomIFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      } catch (final Exception e) {
        Activator.error(e);
      }
    }
  }
  /** For each project in the current build set, reset the version if using project.version */
  @Override
  public Set<Project> applyChanges(final List<Project> projects, final ManipulationSession session)
      throws ManipulationException {
    final ProjectVersionEnforcingState state = session.getState(ProjectVersionEnforcingState.class);
    if (!session.isEnabled()
        || !session.anyStateEnabled(State.activeByDefault)
        || state == null
        || !state.isEnabled()) {
      logger.debug("Project version enforcement is disabled.");
      return Collections.emptySet();
    }

    final Set<Project> changed = new HashSet<Project>();

    for (final Project project : projects) {
      final Model model = project.getModel();

      if (model.getPackaging().equals("pom")) {
        enforceProjectVersion(project, model.getDependencies(), changed);

        if (model.getDependencyManagement() != null) {
          enforceProjectVersion(
              project, model.getDependencyManagement().getDependencies(), changed);
        }

        final List<Profile> profiles = model.getProfiles();
        if (profiles != null) {
          for (final Profile profile : model.getProfiles()) {
            enforceProjectVersion(project, profile.getDependencies(), changed);
            if (profile.getDependencyManagement() != null) {
              enforceProjectVersion(
                  project, profile.getDependencyManagement().getDependencies(), changed);
            }
          }
        }
      }
    }
    if (changed.size() > 0) {
      logger.warn(
          "Using ${project.version} in pom files may lead to unexpected errors with inheritance.");
    }
    return changed;
  }
 /** {@inheritDoc} */
 @Override
 public MavenPomDescriptor scan(Model model, String path, Scope scope, Scanner scanner)
     throws IOException {
   MavenPomDescriptor pomDescriptor = createMavenPomDescriptor(model, scanner);
   ScannerContext scannerContext = scanner.getContext();
   Store store = scannerContext.getStore();
   addParent(pomDescriptor, model, scannerContext);
   addProfiles(pomDescriptor, model, scannerContext);
   addProperties(pomDescriptor, model.getProperties(), store);
   addModules(pomDescriptor, model.getModules(), store);
   addManagedDependencies(
       pomDescriptor,
       model.getDependencyManagement(),
       scannerContext,
       PomManagesDependencyDescriptor.class);
   addDependencies(
       pomDescriptor, model.getDependencies(), PomDependsOnDescriptor.class, scannerContext);
   addManagedPlugins(pomDescriptor, model.getBuild(), scannerContext);
   addPlugins(pomDescriptor, model.getBuild(), scannerContext);
   addLicenses(pomDescriptor, model, store);
   return pomDescriptor;
 }
Exemplo n.º 7
0
 private void checkOnNoDependencieVersion(MavenProject project) throws EnforcerRuleException {
   Model originalModel = project.getOriginalModel();
   StringBuilder dependenciesWithVersionDeclaration = new StringBuilder();
   boolean fail = false;
   for (Dependency d : originalModel.getDependencies()) {
     if (d.getVersion() != null) {
       dependenciesWithVersionDeclaration.append(" - " + d.toString() + "\n");
       fail = true;
     }
   }
   if (fail) {
     throw new EnforcerRuleException(
         "This project contains explicit dependeny versions.\n"
             + "Please declare for maintainance reasons 3rd pary versions in "
             + ignoreMasterProjectGroupId
             + " or\n"
             + "in case of bei '"
             + allowedGroupPrefix
             + "*' Libs in the root pom in the 'dependencyManagement' section.\n"
             + "This dependencies sould be corrected:\n"
             + dependenciesWithVersionDeclaration);
   }
 }
Exemplo n.º 8
0
  /**
   * checks if we need to add a maven dependency for the chosen component and inserts it into the
   * pom.xml if needed
   */
  public static void updateMavenDependencies(
      List<org.fusesource.ide.camel.model.catalog.Dependency> compDeps) throws CoreException {
    RiderDesignEditor editor = Activator.getDiagramEditor();
    if (editor == null) {
      Activator.getLogger()
          .error(
              "Unable to add component dependencies because Editor instance can't be determined.");
      return;
    }

    IProject project = editor.getCamelContextFile().getProject();
    if (project == null) {
      Activator.getLogger()
          .error(
              "Unable to add component dependencies because selected project can't be determined.");
      return;
    }

    IPath pomPathValue =
        project.getProject().getRawLocation() != null
            ? project.getProject().getRawLocation().append("pom.xml")
            : ResourcesPlugin.getWorkspace()
                .getRoot()
                .getLocation()
                .append(project.getFullPath().append("pom.xml"));
    String pomPath = pomPathValue.toOSString();
    final File pomFile = new File(pomPath);
    final Model model = MavenPlugin.getMaven().readModel(pomFile);

    // then check if component dependency is already a dep
    ArrayList<org.fusesource.ide.camel.model.catalog.Dependency> missingDeps =
        new ArrayList<org.fusesource.ide.camel.model.catalog.Dependency>();
    List<Dependency> deps = model.getDependencies();
    for (org.fusesource.ide.camel.model.catalog.Dependency conDep : compDeps) {
      boolean found = false;
      for (Dependency pomDep : deps) {
        if (pomDep.getGroupId().equalsIgnoreCase(conDep.getGroupId())
            && pomDep.getArtifactId().equalsIgnoreCase(conDep.getArtifactId())) {
          // check for correct version
          if (pomDep.getVersion().equalsIgnoreCase(conDep.getVersion()) == false) {
            // not the correct version - change it to fit
            pomDep.setVersion(conDep.getVersion());
          }
          found = true;
          break;
        }
      }
      if (!found) {
        missingDeps.add(conDep);
      }
    }

    for (org.fusesource.ide.camel.model.catalog.Dependency missDep : missingDeps) {
      Dependency dep = new Dependency();
      dep.setGroupId(missDep.getGroupId());
      dep.setArtifactId(missDep.getArtifactId());
      dep.setVersion(missDep.getVersion());
      model.addDependency(dep);
    }

    if (missingDeps.size() > 0) {
      OutputStream os = null;
      try {
        os = new BufferedOutputStream(new FileOutputStream(pomFile));
        MavenPlugin.getMaven().writeModel(model, os);
        IFile pomIFile = project.getProject().getFile("pom.xml");
        if (pomIFile != null) {
          pomIFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        }
      } catch (Exception ex) {
        Activator.getLogger().error(ex);
      } finally {
        try {
          if (os != null) {
            os.close();
          }
        } catch (IOException e) {
          Activator.getLogger().error(e);
        }
      }
    }
  }
Exemplo n.º 9
0
 private void listDependencies(Model model, List<Resource<?>> children) {
   for (Dependency dep : model.getDependencies()) {
     children.add(new MavenDependencyResourceImpl(getResourceFactory(), this, dep));
   }
 }
  private DefaultCoreExtension parseMavenPom(
      URL descriptorUrl, DefaultCoreExtensionRepository repository)
      throws IOException, XmlPullParserException {
    DefaultCoreExtension coreExtension = null;

    InputStream descriptorStream = descriptorUrl.openStream();
    try {
      MavenXpp3Reader reader = new MavenXpp3Reader();
      Model mavenModel = reader.read(descriptorStream);

      String version = resolveVersion(mavenModel.getVersion(), mavenModel, false);
      String groupId = resolveGroupId(mavenModel.getGroupId(), mavenModel, false);

      URL extensionURL = getExtensionURL(descriptorUrl);

      coreExtension =
          new MavenCoreExtension(
              repository,
              extensionURL,
              new ExtensionId(groupId + ':' + mavenModel.getArtifactId(), version),
              packagingToType(mavenModel.getPackaging()),
              mavenModel);

      coreExtension.setName(mavenModel.getName());
      coreExtension.setSummary(mavenModel.getDescription());
      for (Developer developer : mavenModel.getDevelopers()) {
        URL authorURL = null;
        if (developer.getUrl() != null) {
          try {
            authorURL = new URL(developer.getUrl());
          } catch (MalformedURLException e) {
            // TODO: log ?
          }
        }

        coreExtension.addAuthor(new DefaultExtensionAuthor(developer.getId(), authorURL));
      }
      coreExtension.setWebsite(mavenModel.getUrl());

      // licenses
      for (License license : mavenModel.getLicenses()) {
        coreExtension.addLicense(getExtensionLicense(license));
      }

      // features
      String featuresString = mavenModel.getProperties().getProperty("xwiki.extension.features");
      if (StringUtils.isNotBlank(featuresString)) {
        coreExtension.setFeatures(
            this.converter.<Collection<String>>convert(List.class, featuresString));
      }

      // custom properties
      coreExtension.putProperty("maven.groupId", groupId);
      coreExtension.putProperty("maven.artifactId", mavenModel.getArtifactId());

      // dependencies
      for (Dependency mavenDependency : mavenModel.getDependencies()) {
        if (!mavenDependency.isOptional()
            && (mavenDependency.getScope() == null
                || mavenDependency.getScope().equals("compile")
                || mavenDependency.getScope().equals("runtime"))) {

          String dependencyGroupId = resolveGroupId(mavenDependency.getGroupId(), mavenModel, true);
          String dependencyArtifactId = mavenDependency.getArtifactId();
          String dependencyClassifier = mavenDependency.getClassifier();
          String dependencyVersion = resolveVersion(mavenDependency.getVersion(), mavenModel, true);

          DefaultExtensionDependency extensionDependency =
              new MavenCoreExtensionDependency(
                  toExtensionId(dependencyGroupId, dependencyArtifactId, dependencyClassifier),
                  new DefaultVersionConstraint(dependencyVersion),
                  mavenDependency);

          coreExtension.addDependency(extensionDependency);
        }
      }
    } finally {
      IOUtils.closeQuietly(descriptorStream);
    }

    return coreExtension;
  }
  /** {@inheritDoc} */
  public void execute() throws MojoExecutionException, MojoFailureException {
    MavenXpp3Reader pomReader = new MavenXpp3Reader();
    Model model = null;
    Reader reader = null;
    try {
      reader = ReaderFactory.newXmlReader(project.getFile());
      model = pomReader.read(reader);
    } catch (Exception e) {
      throw new MojoExecutionException("IOException: " + e.getMessage(), e);
    } finally {
      IOUtil.close(reader);
    }

    Set<String> duplicateDependencies = new HashSet<String>();
    if (model.getDependencies() != null) {
      duplicateDependencies = findDuplicateDependencies(model.getDependencies());
    }

    Set<String> duplicateDependenciesManagement = new HashSet<String>();
    if (model.getDependencyManagement() != null
        && model.getDependencyManagement().getDependencies() != null) {
      duplicateDependenciesManagement =
          findDuplicateDependencies(model.getDependencyManagement().getDependencies());
    }

    if (getLog().isInfoEnabled()) {
      StringBuffer sb = new StringBuffer();

      if (!duplicateDependencies.isEmpty()) {
        sb.append("List of duplicate dependencies defined in <dependencies/> in your pom.xml:\n");
        for (Iterator<String> it = duplicateDependencies.iterator(); it.hasNext(); ) {
          String dup = it.next();

          sb.append("\to " + dup);
          if (it.hasNext()) {
            sb.append("\n");
          }
        }
      }

      if (!duplicateDependenciesManagement.isEmpty()) {
        if (sb.length() > 0) {
          sb.append("\n");
        }
        sb.append(
            "List of duplicate dependencies defined in <dependencyManagement/> in "
                + "your pom.xml:\n");
        for (Iterator<String> it = duplicateDependenciesManagement.iterator(); it.hasNext(); ) {
          String dup = it.next();

          sb.append("\to " + dup);
          if (it.hasNext()) {
            sb.append("\n");
          }
        }
      }

      if (sb.length() > 0) {
        getLog().info(sb.toString());
      } else {
        getLog()
            .info(
                "No duplicate dependencies found in <dependencies/> or in <dependencyManagement/>");
      }
    }
  }
Exemplo n.º 12
0
  public CollectResult collectDependencies(
      Task task,
      Dependencies dependencies,
      LocalRepository localRepository,
      RemoteRepositories remoteRepositories) {
    RepositorySystemSession session = getSession(task, localRepository);

    remoteRepositories =
        remoteRepositories == null
            ? AetherUtils.getDefaultRepositories(project)
            : remoteRepositories;

    List<org.sonatype.aether.repository.RemoteRepository> repos =
        ConverterUtils.toRepositories(project, session, remoteRepositories, getRemoteRepoMan());

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRequestContext("project");

    for (org.sonatype.aether.repository.RemoteRepository repo : repos) {
      task.getProject().log("Using remote repository " + repo, Project.MSG_VERBOSE);
      collectRequest.addRepository(repo);
    }

    if (dependencies != null) {
      List<Exclusion> globalExclusions = dependencies.getExclusions();
      Collection<String> ids = new HashSet<String>();

      for (Dependency dep : dependencies.getDependencies()) {
        ids.add(dep.getVersionlessKey());
        collectRequest.addDependency(ConverterUtils.toDependency(dep, globalExclusions, session));
      }

      if (dependencies.getPom() != null) {
        Model model = dependencies.getPom().getModel(task);
        for (org.apache.maven.model.Dependency dep : model.getDependencies()) {
          Dependency dependency = new Dependency();
          dependency.setArtifactId(dep.getArtifactId());
          dependency.setClassifier(dep.getClassifier());
          dependency.setGroupId(dep.getGroupId());
          dependency.setScope(dep.getScope());
          dependency.setType(dep.getType());
          dependency.setVersion(dep.getVersion());
          if (ids.contains(dependency.getVersionlessKey())) {
            continue;
          }
          if (dep.getSystemPath() != null && dep.getSystemPath().length() > 0) {
            dependency.setSystemPath(task.getProject().resolveFile(dep.getSystemPath()));
          }
          for (org.apache.maven.model.Exclusion exc : dep.getExclusions()) {
            Exclusion exclusion = new Exclusion();
            exclusion.setGroupId(exc.getGroupId());
            exclusion.setArtifactId(exc.getArtifactId());
            exclusion.setClassifier("*");
            exclusion.setExtension("*");
            dependency.addExclusion(exclusion);
          }
          collectRequest.addDependency(
              ConverterUtils.toDependency(dependency, globalExclusions, session));
        }
      }
    }

    task.getProject().log("Collecting dependencies", Project.MSG_VERBOSE);

    CollectResult result;
    try {
      result = getSystem().collectDependencies(session, collectRequest);
    } catch (DependencyCollectionException e) {
      throw new BuildException("Could not collect dependencies: " + e.getMessage(), e);
    }

    return result;
  }
Exemplo n.º 13
0
  /**
   * This method uses the local mvn installation to resolve and generate the effective POM As a
   * consequence, the generated POM contains all dependencies (even nested !)
   *
   * @param projectRoot
   * @param mavenDir
   * @return null if a dependency cannot be resolved !!!
   * @throws FileNotFoundException
   * @throws IOException
   * @throws XmlPullParserException
   * @throws InterruptedException
   */
  @Deprecated
  public static String extractClassPathFromPom(String projectRoot, String mavenDir)
      throws FileNotFoundException, IOException, XmlPullParserException, InterruptedException {
    // First step: we execute package the project in order to get all dependencies in .m2 cache
    String outprintlog = "/tmp/" + System.currentTimeMillis();
    System.out.println("Packaging the project to obtain all dependencies in meaven cache...");
    System.out.println("Mvn console: " + outprintlog);

    ProcessBuilder proc1 = new ProcessBuilder("mvn", "package");
    proc1.directory(new File(projectRoot));
    proc1.redirectOutput(new File(outprintlog));
    proc1.redirectError(new File(outprintlog));
    proc1.start().waitFor();

    System.out.println("Generating a pom in order to get all dependencies...");

    ProcessBuilder p2 = new ProcessBuilder("mvn", "help:effective-pom");
    p2.directory(new File(projectRoot));
    p2.redirectOutput(new File(outprintlog));
    p2.redirectError(new File(outprintlog));
    Process proc2 = p2.start();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc2.getInputStream()));

    String s = null;
    String effectivePomReaded = "";
    boolean recordOutputAsXml = false;

    while ((s = stdInput.readLine()) != null) {
      String st = s.trim();
      if (st.startsWith("<?xml")) recordOutputAsXml = true;

      if (recordOutputAsXml) effectivePomReaded += s;

      if (st.endsWith("</project>")) recordOutputAsXml = false;
    }

    StringReader sr = new StringReader(effectivePomReaded);

    try {
      MavenXpp3Reader reader = new MavenXpp3Reader();
      Model model = reader.read(sr);

      String classpath = "";

      for (Dependency dep : model.getDependencies()) {
        String ff =
            mavenDir
                + File.separator
                + dep.getGroupId().replaceAll("\\.", File.separator)
                + File.separator
                + dep.getArtifactId()
                + File.separator
                + dep.getVersion()
                + File.separator
                + dep.getArtifactId()
                + "-"
                + dep.getVersion()
                + ".jar";

        File fff = new File(ff);
        if (!fff.exists()) {
          return null;
        } else {
          classpath += ff + File.pathSeparator;
        }
      }

      return classpath;
    } catch (EOFException e) {
      System.out.println("EOF reached -- no classpath !");
      return "";
    }
  }
Exemplo n.º 14
0
 private void listDependencies(List<Resource<?>> children) {
   Model model = getCurrentModel();
   for (Dependency dep : model.getDependencies()) {
     children.add(new MavenDependencyResource(this, dep));
   }
 }