Java Code Examples for org.apache.maven.project.MavenProject#getParent()

The following examples show how to use org.apache.maven.project.MavenProject#getParent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ByteBuddyMojo.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Makes a best effort of locating the configured Java target version.
 *
 * @param project The relevant Maven project.
 * @return The Java version string of the configured build target version or {@code null} if no explicit configuration was detected.
 */
private static String findJavaVersionString(MavenProject project) {
    while (project != null) {
        String target = project.getProperties().getProperty("maven.compiler.target");
        if (target != null) {
            return target;
        }
        for (org.apache.maven.model.Plugin plugin : CompoundList.of(project.getBuildPlugins(), project.getPluginManagement().getPlugins())) {
            if ("maven-compiler-plugin".equals(plugin.getArtifactId())) {
                if (plugin.getConfiguration() instanceof Xpp3Dom) {
                    Xpp3Dom node = ((Xpp3Dom) plugin.getConfiguration()).getChild("target");
                    if (node != null) {
                        return node.getValue();
                    }
                }
            }
        }
        project = project.getParent();
    }
    return null;
}
 
Example 2
Source File: AggregatingGraphFactory.java    From depgraph-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void buildModuleTree(MavenProject parentProject, GraphBuilder<DependencyNode> graphBuilder) {
  Collection<MavenProject> collectedProjects = parentProject.getCollectedProjects();
  for (MavenProject collectedProject : collectedProjects) {
    MavenProject child = collectedProject;
    MavenProject parent = collectedProject.getParent();

    while (parent != null) {
      DependencyNode parentNode = filterProject(parent);
      DependencyNode childNode = filterProject(child);

      graphBuilder.addEdge(parentNode, childNode);

      // Stop if we reached the original parent project!
      if (parent.equals(parentProject)) {
        break;
      }

      child = parent;
      parent = parent.getParent();
    }
  }
}
 
Example 3
Source File: DependenciesMojo.java    From mangooio with Apache License 2.0 6 votes vote down vote up
private void boms(MavenProject project, Properties props) {
    while (project != null) {
        String artifactId = project.getArtifactId();
        if (isBom(artifactId)) {
            props.setProperty(BOMS + artifactId, coordinates(project.getArtifact()));
        }
        if (project.getDependencyManagement() != null) {
            for (Dependency dependency : project.getDependencyManagement().getDependencies()) {
                if ("import".equals(dependency.getScope())) {
                    props.setProperty(BOMS + dependency.getArtifactId(), coordinates(dependency));
                }
            }
        }
        project = project.getParent();
    }
}
 
Example 4
Source File: RequirePropertyDiverges.java    From extra-enforcer-rules with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the ancestor project which defines the rule.
 *
 * @param project to inspect
 * @return the defining ancestor project.
 */
final MavenProject findDefiningParent( final MavenProject project )
{
    final Xpp3Dom invokingRule = createInvokingRuleDom();
    MavenProject parent = project;
    while ( parent != null )
    {
        final Model model = parent.getOriginalModel();
        final Build build = model.getBuild();
        if ( build != null )
        {
            final List<Xpp3Dom> rules = getRuleConfigurations( build );
            if ( isDefiningProject( rules, invokingRule ) )
            {
                break;
            }
        }
        parent = parent.getParent();
    }
    return parent;
}
 
Example 5
Source File: RequirePropertyDiverges.java    From extra-enforcer-rules with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the value of the project against the one given in the defining ancestor project.
 *
 * @param project
 * @param parent
 * @param helper
 * @param propValue
 * @throws EnforcerRuleException
 */
void checkAgainstParentValue( final MavenProject project, final MavenProject parent, EnforcerRuleHelper helper,
        Object propValue ) throws EnforcerRuleException
{
    final StringBuilder parentHierarchy = new StringBuilder( "project." );
    MavenProject needle = project;
    while ( !needle.equals( parent ) )
    {
        parentHierarchy.append( "parent." );
        needle = needle.getParent();
    }
    final String propertyNameInParent = property.replace( "project.", parentHierarchy.toString() );
    Object parentValue = getPropertyValue( helper, propertyNameInParent );
    if ( propValue.equals( parentValue ) )
    {
        final String errorMessage = createResultingErrorMessage( String.format(
                "Property '%s' evaluates to '%s'. This does match '%s' from parent %s",
                property, propValue, parentValue, parent ) );
        throw new EnforcerRuleException( errorMessage );
    }
}
 
Example 6
Source File: DeployMojo.java    From ci.maven with Apache License 2.0 6 votes vote down vote up
private boolean mavenWarPluginExists(MavenProject proj) {
    MavenProject currentProject = proj;
    while(currentProject != null) {
        List<Object> plugins = new ArrayList<Object>(currentProject.getBuildPlugins());
        plugins.addAll(currentProject.getPluginManagement().getPlugins());
        for(Object o : plugins) {
            if(o instanceof Plugin) {
                Plugin plugin = (Plugin) o;
                if(plugin.getGroupId().equals("org.apache.maven.plugins") && plugin.getArtifactId().equals("maven-war-plugin")) {
                    return true;
                }
            }
        }
        currentProject = currentProject.getParent();
    }
    return false;
}
 
Example 7
Source File: ApplyMojo.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the root project folder
 */
protected File getRootProjectFolder() {
    File answer = null;
    MavenProject project = getProject();
    while (project != null) {
        File basedir = project.getBasedir();
        if (basedir != null) {
            answer = basedir;
        }
        project = project.getParent();
    }
    return answer;
}
 
Example 8
Source File: ScmMojo.java    From pitest with Apache License 2.0 5 votes vote down vote up
private File findScmRootDir() {
  MavenProject rootProject = this.getProject();
  while (rootProject.hasParent() && rootProject.getParent().getBasedir() != null) {
    rootProject = rootProject.getParent();
  }
  return rootProject.getBasedir();
}
 
Example 9
Source File: AggregatingGraphFactoryTest.java    From depgraph-maven-plugin with Apache License 2.0 5 votes vote down vote up
private MavenProject createMavenProject(String artifactId, MavenProject parent) {
  MavenProject project = createMavenProject(artifactId);
  project.setParent(parent);
  parent.getModules().add(artifactId);

  MavenProject currentParent = parent;
  while (currentParent != null) {
    currentParent.getCollectedProjects().add(project);
    currentParent = currentParent.getParent();
  }

  return project;
}
 
Example 10
Source File: EnforceVersionsMojo.java    From gitflow-helper-maven-plugin with Apache License 2.0 5 votes vote down vote up
private boolean hasSnapshotInModel(final MavenProject project) {
    MavenProject parent = project.getParent();

    boolean projectIsSnapshot = ArtifactUtils.isSnapshot(project.getVersion());
    boolean parentIsSnapshot = parent != null && hasSnapshotInModel(parent);

    return projectIsSnapshot || parentIsSnapshot;
}
 
Example 11
Source File: DisplayPluginUpdatesMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all the parent projects of the specified project, with the root project first.
 *
 * @param project The maven project to get the parents of
 * @return the parent projects of the specified project, with the root project first.
 * @throws org.apache.maven.plugin.MojoExecutionException if the super-pom could not be created.
 * @since 1.0-alpha-1
 */
private List<MavenProject> getParentProjects( MavenProject project )
    throws MojoExecutionException
{
    List<MavenProject> parents = new ArrayList<>();
    while ( project.getParent() != null )
    {
        project = project.getParent();
        parents.add( 0, project );
    }
    return parents;
}
 
Example 12
Source File: GitUtil.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * utility to find the root project
 *
 * @param project - the project whose root {@link MavenProject} need to be determined
 * @return root MavenProject of the project
 */
public static MavenProject getRootProject(MavenProject project) {
    while (project != null) {
        MavenProject parent = project.getParent();
        if (parent == null) {
            break;
        }
        project = parent;
    }
    return project;
}
 
Example 13
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves meta for an artifact. This method essentially does what an 'effective pom' would do,
 * but for an artifact instead of a project. This method will attempt to resolve metadata at
 * the lowest level of the inheritance tree and work its way up.
 * @param artifact the artifact to resolve metadata for
 * @param project the associated project for the artifact
 * @param component the component to populate data for
 */
private void getClosestMetadata(Artifact artifact, MavenProject project, Component component) {
    extractMetadata(project, component);
    if (project.getParent() != null) {
        getClosestMetadata(artifact, project.getParent(), component);
    } else if (project.getModel().getParent() != null) {
        final MavenProject parentProject = retrieveParentProject(artifact, project);
        if (parentProject != null) {
            getClosestMetadata(artifact, parentProject, component);
        }
    }
}
 
Example 14
Source File: MavenHelper.java    From cyclonedx-gradle-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves meta for an artifact. This method essentially does what an 'effective pom' would do,
 * but for an artifact instead of a project. This method will attempt to resolve metadata at
 * the lowest level of the inheritance tree and work its way up.
 * @param artifact the artifact to resolve metadata for
 * @param project the associated project for the artifact
 * @param component the component to populate data for
 */
void getClosestMetadata(ResolvedArtifact artifact, MavenProject project, Component component) {
    extractMetadata(project, component);
    if (project.getParent() != null) {
        getClosestMetadata(artifact, project.getParent(), component);
    } else if (project.getModel().getParent() != null) {
        final MavenProject parentProject = retrieveParentProject(artifact, project);
        if (parentProject != null) {
            getClosestMetadata(artifact, parentProject, component);
        }
    }
}
 
Example 15
Source File: MavenProjectSettingsConfigurator.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private List<File> getSearchFolders(ProjectConfigurationRequest request) {
	List<File> files = new ArrayList<>();
	MavenProject project = request.getMavenProject();
	while (project != null && project.getBasedir() != null) {
		files.add(project.getBasedir());
		project = project.getParent();
	}
	return files;
}
 
Example 16
Source File: MavenUtil.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static String lookupVersion(final MavenProject project, final MavenDependency mavenDependency) throws MojoExecutionException {
  final DependencyManagement dependencyManagement = project.getModel().getDependencyManagement();
  if (dependencyManagement != null)
    for (final Dependency dependency : dependencyManagement.getDependencies())
      if (dependency.getGroupId().equals(mavenDependency.getGroupId()) && dependency.getArtifactId().equals(mavenDependency.getArtifactId()))
        return dependency.getVersion();

  if (project.getParent() == null)
    throw new MojoExecutionException("Was not able to find the version of: " + mavenDependency.getGroupId() + ":" + mavenDependency.getArtifactId());

  return lookupVersion(project.getParent(), mavenDependency);
}
 
Example 17
Source File: GitUtil.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * utility to find the root project
 *
 * @param project - the project whose root {@link MavenProject} need to be determined
 * @return root MavenProject of the project
 */
public static MavenProject getRootProject(MavenProject project) {
    while (project != null) {
        MavenProject parent = project.getParent();
        if (parent == null) {
            break;
        }
        project = parent;
    }
    return project;
}
 
Example 18
Source File: RootDirMojo.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private Collection<MavenProject> gatherWholeReactor() {
    Set<MavenProject> toProcess = Collections.newSetFromMap(new IdentityHashMap<>());
    for (MavenProject reactorProject : reactorProjects) {
        toProcess.add(reactorProject);
        MavenProject parent = reactorProject.getParent();
        while (parent != null) {
            toProcess.add(parent);
            parent = parent.getParent();
        }
    }

    getLog().info("Processing " + toProcess.size() + " project to find root");
    return toProcess;
}
 
Example 19
Source File: MavenUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Retrieves the URL used for documentation from the provided {@link MavenProject}.
 *
 * @param project MavenProject from which to retrieve the documentation URL
 * @return the documentation URL
 */
public static String getDocumentationUrl(MavenProject project) {
    while (project != null) {
        DistributionManagement distributionManagement = project.getDistributionManagement();
        if (distributionManagement != null) {
            Site site = distributionManagement.getSite();
            if (site != null) {
                return site.getUrl();
            }
        }
        project = project.getParent();
    }
    return null;
}
 
Example 20
Source File: MavenUtils.java    From mvn-golang with Apache License 2.0 4 votes vote down vote up
/**
   * Scan project dependencies to find artifacts generated by mvn golang
   * project.
   *
   * @param mavenProject maven project, must not be null
   * @param includeTestDependencies flag to process dependencies marked for test
   * phases
   * @param mojo calling mojo, must not be null
   * @param session maven session, must not be null
   * @param execution maven execution, must not be null
   * @param resolver artifact resolver, must not be null
   * @param remoteRepositories list of remote repositories, must not be null
   * @return list of files found in artifacts generated by mvn golang plugin
   * @throws ArtifactResolverException exception thrown if some artifact can't
   * be resolved
   */
  @Nonnull
  @MustNotContainNull
  public static List<Tuple<Artifact, File>> scanForMvnGoArtifacts(
          @Nonnull final MavenProject mavenProject,
          final boolean includeTestDependencies,
          @Nonnull final AbstractMojo mojo,
          @Nonnull final MavenSession session,
          @Nonnull final MojoExecution execution,
          @Nonnull final ArtifactResolver resolver,
          @Nonnull @MustNotContainNull final List<ArtifactRepository> remoteRepositories
  ) throws ArtifactResolverException {
    final List<Tuple<Artifact, File>> result = new ArrayList<>();
//    final String phase = execution.getLifecyclePhase();

    final Set<String> alreadyFoundArtifactRecords = new HashSet<>();

    MavenProject currentProject = mavenProject;
    while (currentProject != null && !Thread.currentThread().isInterrupted()) {
      final Set<Artifact> projectDependencies = currentProject.getDependencyArtifacts();
      final List<Artifact> artifacts = new ArrayList<>(projectDependencies == null ? Collections.emptySet() : projectDependencies);
      mojo.getLog().debug("Detected dependency artifacts: " + artifacts);

      while (!artifacts.isEmpty() && !Thread.currentThread().isInterrupted()) {
        final Artifact artifact = artifacts.remove(0);

        if (Artifact.SCOPE_TEST.equals(artifact.getScope()) && !includeTestDependencies) {
          continue;
        }

        if (artifact.getType().equals(AbstractGolangMojo.GOARTIFACT_PACKAGING)) {
          final ArtifactResult artifactResult = resolver.resolveArtifact(makeResolveArtifactProjectBuildingRequest(session, remoteRepositories), artifact);
          final File zipFillePath = artifactResult.getArtifact().getFile();

          mojo.getLog().debug("Detected MVN-GOLANG marker inside ZIP dependency: " + artifact.getGroupId() + ':' + artifact.getArtifactId() + ':' + artifact.getVersion() + ':' + artifact.getType());

          if (ZipUtil.containsEntry(zipFillePath, GolangMvnInstallMojo.MVNGOLANG_DEPENDENCIES_FILE)) {
            final byte[] artifactFlagFile = ZipUtil.unpackEntry(zipFillePath, GolangMvnInstallMojo.MVNGOLANG_DEPENDENCIES_FILE, StandardCharsets.UTF_8);

            for (final String str : new String(artifactFlagFile, StandardCharsets.UTF_8).split("\\R")) {
              if (str.trim().isEmpty() || alreadyFoundArtifactRecords.contains(str)) {
                continue;
              }
              mojo.getLog().debug("Adding mvn-golang dependency: " + str);
              alreadyFoundArtifactRecords.add(str);
              try {
                artifacts.add(parseArtifactRecord(str, new MvnGolangArtifactHandler()));
              } catch (InvalidVersionSpecificationException ex) {
                throw new ArtifactResolverException("Can't make artifact: " + str, ex);
              }
            }
          }

          final File artifactFile = artifactResult.getArtifact().getFile();
          mojo.getLog().debug("Artifact file: " + artifactFile);
          if (doesContainFile(result, artifactFile)) {
            mojo.getLog().debug("Artifact file ignored as duplication: " + artifactFile);
          } else {
            result.add(Tuple.of(artifact, artifactFile));
          }
        }
      }
      currentProject = currentProject.hasParent() ? currentProject.getParent() : null;
    }

    return result;
  }