private void listProfiles(List<Resource<?>> children) {
   Model model = getCurrentModel();
   List<Profile> profiles = model.getProfiles();
   for (Profile profile : profiles) {
     children.add(new MavenProfileResource(this, profile));
   }
 }
Example #2
0
 private void checkOnNoDependencieVersionsFrom3rdParty(MavenProject project)
     throws EnforcerRuleException {
   Model originalModel = project.getOriginalModel();
   StringBuilder dependenciesWithVersionDeclaration = new StringBuilder();
   if (project.getGroupId().equals(ignoreMasterProjectGroupId)
       || originalModel.getDependencyManagement() == null
       || originalModel.getDependencyManagement().getDependencies() == null) {
     return;
   }
   boolean fail = false;
   for (Dependency d : originalModel.getDependencyManagement().getDependencies()) {
     if (!d.getGroupId().startsWith(allowedGroupPrefix)) {
       dependenciesWithVersionDeclaration.append(" - " + d.toString() + "\n");
       fail = true;
     }
   }
   if (fail) {
     throw new EnforcerRuleException(
         "This Project contains Dependency-Versions from 3rd party libs (not "
             + allowedGroupPrefix
             + ").\n"
             + "Please declare for maintainance reasons 3rd pary versions in "
             + ignoreMasterProjectGroupId
             + ".\n"
             + "This dependencies sould be corrected:\n"
             + dependenciesWithVersionDeclaration);
   }
 }
Example #3
0
  @Command("remove-parent")
  public void removeParent(final PipeOut out) {
    MavenCoreFacet mvn = project.getFacet(MavenCoreFacet.class);

    Model pom = mvn.getPOM();
    Parent parent = pom.getParent();

    if (parent != null) {
      String parentId =
          parent.getGroupId()
              + ":"
              + parent.getArtifactId()
              + ":"
              + parent.getVersion()
              + " ("
              + (parent.getRelativePath() == null ? " " : parent.getRelativePath() + ")");

      if (shell.promptBoolean(
          "Are you sure you want to remove all parent information from this project? [ "
              + parentId
              + "]",
          false)) {
        out.println("Removed parent [ " + parentId + " ]");
        pom.setParent(null);
        mvn.setPOM(pom);
      } else {
        out.println("Aborted...");
      }
    } else {
      out.println("Nothing to remove...");
    }
  }
Example #4
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();
 }
  @Test
  public void autoDiscoverWithOneCompleteLocationFromMirrorWithEncryptedPassword()
      throws NexusDiscoveryException {
    Settings settings = new Settings();

    String url = "http://nexus.somewhere.com/";

    testClientManager.testUrl = url;
    testClientManager.testUser = "******";
    testClientManager.testPassword = "******";

    Mirror mirror = new Mirror();
    mirror.setId("some-mirror");
    mirror.setName("A Mirror");
    mirror.setUrl(url);

    settings.addMirror(mirror);

    Server server = new Server();
    server.setId("some-mirror");
    server.setUsername("user");
    server.setPassword(encryptedPassword);

    settings.addServer(server);

    Model model = new Model();
    model.setModelVersion("4.0.0");
    model.setGroupId("group.id");
    model.setArtifactId("artifact-id");
    model.setVersion("1");

    MavenProject project = new MavenProject(model);

    discovery.discover(settings, project, "blah", true);
  }
  @Override
  public boolean updateModel(Model model) throws MavenExecutionException {
    Map<String, String> versionOverrides = getVersionOverrides();
    if (versionOverrides.size() == 0) {
      return false;
    }

    // If the model doesn't have any plugin management set by default, create one for it
    PluginManagement pluginManagement = model.getBuild().getPluginManagement();
    if (pluginManagement == null) {
      pluginManagement = new PluginManagement();
      model.getBuild().setPluginManagement(pluginManagement);
      Log.getLog().debug("Created new Plugin Management for model");
    }

    // Override plugin management versions
    applyOverrides(pluginManagement.getPlugins(), versionOverrides);

    // Override plugin versions
    List<Plugin> projectPlugins = model.getBuild().getPlugins();
    applyOverrides(projectPlugins, versionOverrides);

    // Include the overrides in the built files for repeatability
    writeOverrideMap(model, getName(), versionOverrides);

    // Assuming the Model changed since overrides were given
    return true;
  }
  private String resolveVersion(String modelVersion, Model mavenModel, boolean dependency) {
    String version = modelVersion;

    // TODO: download parents and resolve pom.xml properties using aether ? could be pretty
    // expensive for
    // the init
    if (version == null) {
      if (!dependency) {
        Parent parent = mavenModel.getParent();

        if (parent != null) {
          version = parent.getVersion();
        }
      }
    } else if (version.startsWith("$")) {
      String propertyName = version.substring(2, version.length() - 1);

      if (propertyName.equals("project.version")
          || propertyName.equals("pom.version")
          || propertyName.equals("version")) {
        version = resolveVersion(mavenModel.getVersion(), mavenModel, false);
      } else {
        String value = mavenModel.getProperties().getProperty(propertyName);
        if (value != null) {
          version = value;
        }
      }
    }

    if (version == null) {
      version = UNKNOWN;
    }

    return version;
  }
  private String resolveGroupId(String modelGroupId, Model mavenModel, boolean dependency) {
    String groupId = modelGroupId;

    // TODO: download parents and resolve pom.xml properties using aether ? could be pretty
    // expensive for
    // the init
    if (groupId == null) {
      if (!dependency) {
        Parent parent = mavenModel.getParent();

        if (parent != null) {
          groupId = parent.getGroupId();
        }
      }
    } else if (groupId.startsWith("$")) {
      String propertyName = groupId.substring(2, groupId.length() - 1);

      String value = mavenModel.getProperties().getProperty(propertyName);
      if (value != null) {
        groupId = value;
      }
    }

    if (groupId == null) {
      groupId = UNKNOWN;
    }

    return groupId;
  }
 @Override
 public void addPlugin(MavenPlugin plugin) {
   MavenCoreFacet mavenCoreFacet = project.getFacet(MavenCoreFacet.class);
   Model pom = mavenCoreFacet.getPOM();
   pom.getBuild().addPlugin(new MavenPluginAdapter(plugin));
   mavenCoreFacet.setPOM(pom);
 }
Example #10
0
 public void setUp() throws Exception {
   mojo = new CopyModulesMojo();
   model = new Model();
   project = new MavenProject(model);
   properties = new Properties();
   model.setProperties(properties);
   model.setPackaging("war");
 }
  @Override
  public void execute() throws Exception {
    final File pom = new File(testExecutionDirectory, "pom.xml");

    final Model model = getModel(pom);
    model.setVersion(model.getVersion() + "-SNAPSHOT");
    persistModel(pom, model);
  }
 private static MavenProject createProject(String artifactId, String version, File file) {
   Model model = new Model();
   model.setGroupId("groupId");
   model.setArtifactId(artifactId);
   model.setVersion(version);
   MavenProject project = new MavenProject(model);
   project.setFile(file);
   return project;
 }
 /**
  * Create the fully qualified name of the model (using packaging type "pom").
  *
  * @param model The model.
  * @return The fully qualified name.
  */
 private String getFullyQualifiedName(Model model) {
   StringBuilder id = new StringBuilder();
   id.append((model.getGroupId() == null) ? "[inherited]" : model.getGroupId());
   id.append(":");
   id.append(model.getArtifactId());
   id.append(":pom:");
   id.append((model.getVersion() == null) ? "[inherited]" : model.getVersion());
   return id.toString();
 }
 /*
  * (non-Javadoc)
  *
  * @see org.jboss.forge.addon.deltaspike.facets.DeltaSpikeFacet#setDeltaSpikeVersion(java.lang.String)
  */
 @Override
 public DeltaSpikeFacet setDeltaSpikeVersion(String version) {
   MavenFacet mavenFacet = getFaceted().getFacet(MavenFacet.class);
   Model model = mavenFacet.getModel();
   model.getProperties().put(DELTASPIKE_PROPERTY, version);
   // force write of changes
   mavenFacet.setModel(model);
   return this;
 }
Example #15
0
 @Override
 public String getBasePackage() {
   Model model = getFaceted().getFacet(MavenFacet.class).getModel();
   String groupId = model.getGroupId();
   if (groupId == null) {
     groupId = model.getParent().getGroupId();
   }
   return Packages.toValidPackageName(groupId);
 }
 @SuppressWarnings("nls")
 protected void addProperties(Model model) {
   // set the properties
   Properties p = model.getProperties();
   if (p == null) {
     p = new Properties();
     model.setProperties(p);
   }
 }
  /**
   * Resolves a Maven artifact, given its coordinates, by looking it up in dependency management
   * section of POM in which the test resides.
   *
   * @param groupId Maven group id of artifact to be resolved
   * @param artifactId Maven artifact id of artifact to be resolved
   * @param type Maven type of artifact to be resolved. If not specified (null), type is not
   *     considered while finding the dependency in dependency management
   * @param classifier Maven classifier of artifact to be resolved. If not specified (null),
   *     classifier is not considered while finding the dependency in dependency management
   * @param overrideType an optional type to be used to override the type specified in dependency
   *     management (e.g nexus-plugin -> zip)
   * @param overrideClassifier an optional classifier to override the classifier specified in
   *     dependency management (e.g (not specified) -> bundle)
   * @return resolved artifact file
   */
  public File resolveFromDependencyManagement(
      final String groupId,
      final String artifactId,
      final String type,
      final String classifier,
      final String overrideType,
      final String overrideClassifier) {
    try {
      final Model model = modelResolver.resolveModel(model().pom(testProjectPomFile));

      if (model.getDependencyManagement() != null) {
        final List<Dependency> dependencies = model.getDependencyManagement().getDependencies();

        for (Dependency dependency : dependencies) {
          if (!dependency.getGroupId().equalsIgnoreCase(groupId)) {
            continue;
          }
          if (!dependency.getArtifactId().equalsIgnoreCase(artifactId)) {
            continue;
          }
          if (type != null && !dependency.getType().equals(type)) {
            continue;
          }
          if (classifier != null && !dependency.getClassifier().equals(classifier)) {
            continue;
          }

          StringBuilder coordinates = new StringBuilder();
          coordinates.append(dependency.getGroupId());
          coordinates.append(":").append(dependency.getArtifactId());

          String rExtension = dependency.getType();
          if (overrideType != null) {
            rExtension = overrideType;
          }
          if (rExtension != null) {
            coordinates.append(":").append(rExtension);
          }

          String rClassifier = dependency.getClassifier();
          if (overrideClassifier != null) {
            rClassifier = overrideClassifier;
          }
          if (rClassifier != null) {
            coordinates.append(":").append(rClassifier);
          }
          coordinates.append(":").append(dependency.getVersion());
          return resolveArtifact(coordinates.toString());
        }
      }
      throw new RuntimeException(
          String.format("Dependency %s:%s was not found", groupId, artifactId));
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
  @Test
  public void testTPCNotExists() throws Exception {
    final Model model = new Model();
    final List<Model> hierarchy = asList(model);

    tpcAssembler.assembleTPCInheritance(hierarchy);

    assertSame(model, hierarchy.get(0));
    assertNull(model.getBuild());
  }
  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;
  }
Example #20
0
 @Test
 public void testModelWriter() throws Exception {
   StringWriter sw = new StringWriter();
   ModelWriter writer = new YamlModelWriter();
   Model model = getModel();
   Properties p = new Properties();
   p.setProperty("FOO", "BAR");
   model.setProperties(p);
   writer.write(sw, null, model);
   // System.out.println(sw.toString());
 }
  @Test
  public void testJacocoCommands() throws Exception {

    Project project = initializeJavaProject();
    Dependency junitDep = new Dependency();
    junitDep.setArtifactId("junit");
    junitDep.setGroupId("junit");
    junitDep.setVersion("4.10");
    junitDep.setScope("test");
    MavenCoreFacet facet = project.getFacet(MavenCoreFacet.class);
    Model pom = facet.getPOM();
    pom.addDependency(junitDep);
    facet.setPOM(pom);

    queueInputLines("");
    // create some simple classes
    getShell().execute("java new-class --package com.test \"public class A {}\"");
    getShell().execute("java new-field \"private int numberA=1;\"");
    getShell().execute("java new-method  \"public int getNumberA(){return numberA;}\"");

    getShell().execute("java new-class --package com.test \"public class B {}\"");
    getShell().execute("java new-field \"private int numberB=2;\"");
    getShell().execute("java new-method  \"public int getNumberB(){return numberB;}\"");

    // create and copy test class
    getShell()
        .execute(
            "java new-class --package com.test \"package com.test; import org.junit.Test;import static org.junit.Assert.*; public class ABTest {}\"");
    getShell()
        .execute(
            "java new-method  \"@Test public void testClasses(){A a = new A();B b = new B();assertEquals(3,a.getNumberA()+b.getNumberB());}\"");
    getShell().execute("cd " + project.getProjectRoot().getFullyQualifiedName());
    getShell().execute("cp src/main/java/com/test/ABTest.java src/test/java/");
    getShell().execute("rm -rf src/main/java/com/test/ABTest.java");

    // run jacoco plugin commands
    getShell().execute("jacoco setup");
    getShell().execute("jacoco run-tests --package com.test");
    queueInputLines("N");
    getShell().execute("jacoco create-report");

    assertTrue(
        "Missing jacoco.exec file!",
        project.getProjectRoot().getChildDirectory("target").getChild("jacoco.exec").exists());
    assertTrue(
        "Missing index.html report file!",
        project
            .getProjectRoot()
            .getChildDirectory("target")
            .getChildDirectory("site")
            .getChildDirectory("jacoco")
            .getChild("index.html")
            .exists());
  }
 @Override
 public void removePlugin(Dependency dependency) {
   MavenCoreFacet mavenCoreFacet = project.getFacet(MavenCoreFacet.class);
   List<Plugin> pomPlugins = mavenCoreFacet.getPOM().getBuild().getPlugins();
   for (Plugin pomPlugin : pomPlugins) {
     if (pomPlugin.getGroupId().equals(dependency.getGroupId())
         && pomPlugin.getArtifactId().equals(dependency.getArtifactId())) {
       Model pom = mavenCoreFacet.getPOM();
       pom.getBuild().removePlugin(pomPlugin);
       mavenCoreFacet.setPOM(pom);
     }
   }
 }
  @Override
  public boolean install() {
    if (!this.isInstalled()) {
      for (DirectoryResource folder : this.getSourceFolders()) {
        folder.mkdirs();
      }

      // FIXME WOW this needs to be simplified somehow...
      MavenCoreFacet maven = project.getFacet(MavenCoreFacet.class);
      Model pom = maven.getPOM();
      Build build = pom.getBuild();
      if (build == null) {
        build = new Build();
      }
      List<Plugin> plugins = build.getPlugins();
      Plugin javaSourcePlugin = null;
      for (Plugin plugin : plugins) {
        if ("org.apache.maven.plugins".equals(plugin.getGroupId())
            && "maven-compiler-plugin".equals(plugin.getArtifactId())) {
          javaSourcePlugin = plugin;
        }
      }

      if (javaSourcePlugin == null) {
        javaSourcePlugin = new Plugin();
        // FIXME this should find the most recent version using DependencyResolver
        javaSourcePlugin.setGroupId("org.apache.maven.plugins");
        javaSourcePlugin.setArtifactId("maven-compiler-plugin");
        javaSourcePlugin.setVersion("2.3.2");

        try {
          Xpp3Dom dom =
              Xpp3DomBuilder.build(
                  new ByteArrayInputStream(
                      "<configuration><source>1.6</source><target>1.6</target></configuration>"
                          .getBytes()),
                  "UTF-8");

          javaSourcePlugin.setConfiguration(dom);
        } catch (Exception e) {
          throw new ProjectModelException(e);
        }
      }

      build.addPlugin(javaSourcePlugin);
      pom.setBuild(build);
      maven.setPOM(pom);
    }
    return true;
  }
Example #24
0
  @Command("set-artifactid")
  public void setArtifactId(
      final PipeOut out,
      @Option(description = "the new artifactId; for example: \"forge-shell\"")
          final String artifactId) {
    Assert.notNull(artifactId, "GroupId must not be empty");

    MavenCoreFacet mvn = project.getFacet(MavenCoreFacet.class);

    Model pom = mvn.getPOM();
    pom.setArtifactId(artifactId);
    mvn.setPOM(pom);
    out.println("Set artifactId [ " + artifactId + " ]");
  }
Example #25
0
  @Command("set-version")
  public void setVersion(
      final PipeOut out,
      @Option(description = "the new version; for example: \"1.0.0.Final\"") final String version) {
    Assert.notNull(version, "GroupId must not be empty");

    MavenCoreFacet mvn = project.getFacet(MavenCoreFacet.class);

    Model pom = mvn.getPOM();
    pom.setVersion(version);
    mvn.setPOM(pom);

    out.println("Set version [ " + version + " ]");
  }
Example #26
0
  @Command("set-groupid")
  public void setGroupId(
      final PipeOut out,
      @Option(description = "the new groupId; for example: \"org.jboss.forge\"")
          final String groupId) {
    Assert.notNull(groupId, "GroupId must not be empty");

    MavenCoreFacet mvn = project.getFacet(MavenCoreFacet.class);

    Model pom = mvn.getPOM();
    pom.setGroupId(groupId);
    mvn.setPOM(pom);
    out.println("Set groupId [ " + groupId + " ]");
  }
  @Test
  public void testSetupCommand() throws Exception {
    Project project = initializeJavaProject();
    getShell().execute("jacoco setup");
    MavenCoreFacet facet = project.getFacet(MavenCoreFacet.class);
    Model pom = facet.getPOM();
    Profile jacocoProfile = pom.getProfiles().get(0);
    assertEquals("jacoco", jacocoProfile.getId());

    Plugin jacocoPlugin = jacocoProfile.getBuild().getPlugins().get(0);
    assertEquals("jacoco-maven-plugin", jacocoPlugin.getArtifactId());

    PluginExecution exec = jacocoPlugin.getExecutions().get(0);
    assertEquals("prepare-agent", exec.getGoals().get(0));
  }
Example #28
0
  public void testIsImpalaModule() throws Exception {
    assertEquals("war", model.getPackaging());

    mojo.setProject(project);
    assertTrue(mojo.isImpalaHost());

    properties.setProperty("impala.host", "false");
    assertFalse(mojo.isImpalaHost());

    properties.setProperty("impala.host", "true");
    assertTrue(mojo.isImpalaHost());

    model.setPackaging("jar");
    assertTrue(mojo.isImpalaHost());
  }
  /**
   * This is a "switchboard" to detech HOW to deploy. For now, just using the protocol from POM's
   * DistributionManagement section and invoking the getWagonHintForDeployProtocol(String protocol)
   * to get the wagon hint.
   *
   * @throws Exception
   */
  protected void deployArtifacts() throws Exception {
    // test the test directory
    File projectsDir = this.getTestResourceAsFile("projects");
    log.debug("projectsDir: " + projectsDir);

    // if null there is nothing to deploy...
    if (projectsDir != null) {

      // we have the parent dir, for each child (one level) we need to grab the pom.xml out of it
      // and parse it,
      // and then deploy the artifact, sounds like fun, right!

      File[] projectFolders = projectsDir.listFiles(MavenProjectFileFilter.INSTANCE);

      // to achieve same ordering on different OSes
      Arrays.sort(projectFolders);

      for (int ii = 0; ii < projectFolders.length; ii++) {
        File project = projectFolders[ii];

        // we already check if the pom.xml was in here.
        File pom = new File(project, "pom.xml");

        MavenXpp3Reader reader = new MavenXpp3Reader();
        FileInputStream fis = new FileInputStream(pom);
        Model model = reader.read(new FileReader(pom));
        fis.close();

        // a helpful note so you don't need to dig into the code to much.
        if (model.getDistributionManagement() == null
            || model.getDistributionManagement().getRepository() == null) {
          Assert.fail(
              "The test artifact is either missing or has an invalid Distribution Management section.");
        }

        // get the URL to deploy
        String deployUrl = model.getDistributionManagement().getRepository().getUrl();

        // get the protocol
        String deployUrlProtocol = deployUrl.substring(0, deployUrl.indexOf(":"));

        // calculate the wagon hint
        String wagonHint = getWagonHintForDeployProtocol(deployUrlProtocol);

        deployArtifacts(project, wagonHint, deployUrl, model);
      }
    }
  }
Example #30
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;
  }