Maven Core classes - the core engine of Apache Maven build system
—
Maven Core project management provides comprehensive APIs for working with Maven projects, including project model access, building, dependency resolution, and project hierarchy management. These APIs enable programmatic access to all aspects of Maven project configuration and structure.
The central representation of a Maven project, providing access to all project information including model, artifacts, dependencies, and build paths.
public class MavenProject implements Cloneable {
/**
* Get the project's main artifact.
*/
public Artifact getArtifact();
/**
* Set the project's main artifact.
*/
public void setArtifact(Artifact artifact);
/**
* Get the project object model (POM).
*/
public Model getModel();
/**
* Set the project object model.
*/
public void setModel(Model model);
// Project Identity
public String getGroupId();
public String getArtifactId();
public String getVersion();
public String getName();
public String getDescription();
public String getUrl();
// Project Structure
public File getFile();
public File getBasedir();
public String getPackaging();
// Parent/Child Relationships
public MavenProject getParent();
public void setParent(MavenProject parent);
public List<MavenProject> getCollectedProjects();
public void setCollectedProjects(List<MavenProject> collectedProjects);
// Dependencies
public List<Dependency> getDependencies();
public List<Dependency> getCompileDependencies();
public List<Dependency> getTestDependencies();
public List<Dependency> getRuntimeDependencies();
// Dependency Management
public DependencyManagement getDependencyManagement();
public void setDependencyManagement(DependencyManagement dependencyManagement);
// Build Paths
public List<String> getCompileSourceRoots();
public List<String> getTestCompileSourceRoots();
public List<String> getCompileClasspathElements() throws DependencyResolutionRequiredException;
public List<String> getTestClasspathElements() throws DependencyResolutionRequiredException;
public List<String> getRuntimeClasspathElements() throws DependencyResolutionRequiredException;
public List<String> getSystemClasspathElements() throws DependencyResolutionRequiredException;
// Build Configuration
public Build getBuild();
public void setBuild(Build build);
// Properties
public Properties getProperties();
public void setProperties(Properties properties);
// Profiles
public List<Profile> getActiveProfiles();
public void setActiveProfiles(List<Profile> activeProfiles);
public List<String> getInjectedProfileIds();
// Artifacts
public Set<Artifact> getArtifacts();
public void setArtifacts(Set<Artifact> artifacts);
public Set<Artifact> getDependencyArtifacts();
public void setDependencyArtifacts(Set<Artifact> dependencyArtifacts);
// Attached Artifacts
public List<Artifact> getAttachedArtifacts();
public void addAttachedArtifact(Artifact artifact);
// Plugin Configuration
public List<Plugin> getBuildPlugins();
public Map<String, Plugin> getPluginMap();
public Plugin getPlugin(String pluginKey);
// Reporting
public List<ReportPlugin> getReportPlugins();
public Map<String, ReportPlugin> getReportPluginMap();
// Repositories
public List<Repository> getRepositories();
public List<Repository> getPluginRepositories();
// Project Context
public Object getContextValue(String key);
public void setContextValue(String key, Object value);
// Lifecycle
public void addLifecyclePhase(String lifecycle);
public Set<String> getLifecyclePhases();
}Basic Usage Example:
import org.apache.maven.project.MavenProject;
import org.apache.maven.model.Dependency;
public void analyzeProject(MavenProject project) throws Exception {
// Basic project information
System.out.println("Project: " + project.getGroupId() + ":" +
project.getArtifactId() + ":" + project.getVersion());
System.out.println("Name: " + project.getName());
System.out.println("Packaging: " + project.getPackaging());
System.out.println("Base Directory: " + project.getBasedir());
// Dependencies
System.out.println("Dependencies:");
for (Dependency dep : project.getDependencies()) {
System.out.println(" " + dep.getGroupId() + ":" +
dep.getArtifactId() + ":" + dep.getVersion() +
" (scope: " + dep.getScope() + ")");
}
// Source paths
System.out.println("Compile Source Roots:");
for (String sourceRoot : project.getCompileSourceRoots()) {
System.out.println(" " + sourceRoot);
}
// Classpath elements
System.out.println("Compile Classpath:");
for (String classpathElement : project.getCompileClasspathElements()) {
System.out.println(" " + classpathElement);
}
// Build plugins
System.out.println("Build Plugins:");
for (Plugin plugin : project.getBuildPlugins()) {
System.out.println(" " + plugin.getGroupId() + ":" +
plugin.getArtifactId() + ":" + plugin.getVersion());
}
}Primary interface for building Maven projects from POM files and other sources.
public interface ProjectBuilder {
/**
* Build a single project from a POM file.
*
* @param projectFile the POM file to build from
* @param request build configuration and context
* @return project building result with built project
* @throws ProjectBuildingException if building fails
*/
ProjectBuildingResult build(File projectFile, ProjectBuildingRequest request)
throws ProjectBuildingException;
/**
* Build a project from an artifact coordinate.
*
* @param projectArtifact the artifact to build project for
* @param request build configuration and context
* @return project building result with built project
* @throws ProjectBuildingException if building fails
*/
ProjectBuildingResult build(Artifact projectArtifact, ProjectBuildingRequest request)
throws ProjectBuildingException;
/**
* Build projects from a list of POM files.
*
* @param projectFiles list of POM files to build
* @param recursive whether to include child modules
* @param request build configuration and context
* @return list of project building results
* @throws ProjectBuildingException if any build fails
*/
List<ProjectBuildingResult> build(List<File> projectFiles, boolean recursive,
ProjectBuildingRequest request) throws ProjectBuildingException;
}public interface ProjectBuildingRequest {
// Repository Configuration
ProjectBuildingRequest setLocalRepository(ArtifactRepository localRepository);
ArtifactRepository getLocalRepository();
ProjectBuildingRequest setRemoteRepositories(List<ArtifactRepository> remoteRepositories);
List<ArtifactRepository> getRemoteRepositories();
ProjectBuildingRequest setPluginArtifactRepositories(List<ArtifactRepository> pluginArtifactRepositories);
List<ArtifactRepository> getPluginArtifactRepositories();
// Repository Session
ProjectBuildingRequest setRepositorySession(RepositorySystemSession repositorySession);
RepositorySystemSession getRepositorySession();
// Processing Configuration
ProjectBuildingRequest setProcessPlugins(boolean processPlugins);
boolean isProcessPlugins();
ProjectBuildingRequest setResolveDependencies(boolean resolveDependencies);
boolean isResolveDependencies();
// Validation Configuration
ProjectBuildingRequest setValidationLevel(int validationLevel);
int getValidationLevel();
static final int VALIDATION_LEVEL_MINIMAL = 0;
static final int VALIDATION_LEVEL_MAVEN_2_0 = 20;
static final int VALIDATION_LEVEL_MAVEN_3_0 = 30;
static final int VALIDATION_LEVEL_MAVEN_3_1 = 31;
static final int VALIDATION_LEVEL_STRICT = 100;
// Profile Configuration
ProjectBuildingRequest setActiveProfileIds(List<String> activeProfileIds);
List<String> getActiveProfileIds();
ProjectBuildingRequest setInactiveProfileIds(List<String> inactiveProfileIds);
List<String> getInactiveProfileIds();
ProjectBuildingRequest setProfiles(List<Profile> profiles);
List<Profile> getProfiles();
// Properties
ProjectBuildingRequest setSystemProperties(Properties systemProperties);
Properties getSystemProperties();
ProjectBuildingRequest setUserProperties(Properties userProperties);
Properties getUserProperties();
// Build Start Time
ProjectBuildingRequest setBuildStartTime(Date buildStartTime);
Date getBuildStartTime();
}public interface ProjectBuildingResult {
/**
* Get the project ID that was built.
*/
String getProjectId();
/**
* Get the POM file used for building.
*/
File getPomFile();
/**
* Get the built Maven project.
*/
MavenProject getProject();
/**
* Get any problems that occurred during building.
*/
List<ModelProblem> getProblems();
/**
* Get dependency resolution result if dependencies were resolved.
*/
DependencyResolutionResult getDependencyResolutionResult();
}Project Building Example:
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.project.ProjectBuildingResult;
import org.apache.maven.project.DefaultProjectBuildingRequest;
@Component
private ProjectBuilder projectBuilder;
@Component
private RepositorySystem repositorySystem;
public MavenProject buildProject(File pomFile) throws Exception {
// Create building request
ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
// Configure repository session
DefaultRepositorySystemSession repoSession = new DefaultRepositorySystemSession();
repoSession.setLocalRepositoryManager(
repositorySystem.newLocalRepositoryManager(repoSession, localRepo));
request.setRepositorySession(repoSession);
// Configure repositories
request.setLocalRepository(localRepo);
request.setRemoteRepositories(remoteRepos);
request.setPluginArtifactRepositories(pluginRepos);
// Configure processing options
request.setProcessPlugins(true);
request.setResolveDependencies(true);
request.setValidationLevel(ProjectBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1);
// Set properties
Properties userProps = new Properties();
userProps.setProperty("maven.compiler.source", "17");
userProps.setProperty("maven.compiler.target", "17");
request.setUserProperties(userProps);
// Build project
ProjectBuildingResult result = projectBuilder.build(pomFile, request);
// Check for problems
if (!result.getProblems().isEmpty()) {
System.out.println("Build problems:");
for (ModelProblem problem : result.getProblems()) {
System.out.println(" " + problem.getSeverity() + ": " + problem.getMessage());
}
}
return result.getProject();
}
// Build multiple projects
public List<MavenProject> buildMultiModuleProject(File rootPom) throws Exception {
ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
// ... configure request
List<ProjectBuildingResult> results = projectBuilder.build(
Arrays.asList(rootPom), true, request);
List<MavenProject> projects = new ArrayList<>();
for (ProjectBuildingResult result : results) {
projects.add(result.getProject());
}
return projects;
}Utility interface for manipulating Maven projects and attached artifacts.
public interface MavenProjectHelper {
/**
* Attach an artifact to the project.
*
* @param project the Maven project
* @param artifactFile the artifact file to attach
* @param artifactType the type of artifact (jar, war, etc.)
*/
void attachArtifact(MavenProject project, File artifactFile, String artifactType);
/**
* Attach an artifact with classifier.
*
* @param project the Maven project
* @param artifactFile the artifact file to attach
* @param artifactType the type of artifact
* @param artifactClassifier the classifier (sources, javadoc, etc.)
*/
void attachArtifact(MavenProject project, File artifactFile, String artifactType, String artifactClassifier);
/**
* Attach an existing artifact.
*
* @param project the Maven project
* @param artifact the artifact to attach
* @param artifactFile the file for the artifact
*/
void attachArtifact(MavenProject project, Artifact artifact, File artifactFile);
/**
* Add a resource directory to the project.
*
* @param project the Maven project
* @param resourceDirectory the resource directory to add
* @param includes list of include patterns (can be null)
* @param excludes list of exclude patterns (can be null)
*/
void addResource(MavenProject project, String resourceDirectory, List<String> includes, List<String> excludes);
/**
* Add a test resource directory to the project.
*/
void addTestResource(MavenProject project, String resourceDirectory, List<String> includes, List<String> excludes);
}Project Helper Usage:
import org.apache.maven.project.MavenProjectHelper;
@Component
private MavenProjectHelper projectHelper;
public void processArtifacts(MavenProject project) {
// Attach source JAR
File sourceJar = new File(project.getBuild().getDirectory(),
project.getArtifactId() + "-" + project.getVersion() + "-sources.jar");
if (sourceJar.exists()) {
projectHelper.attachArtifact(project, sourceJar, "jar", "sources");
}
// Attach Javadoc JAR
File javadocJar = new File(project.getBuild().getDirectory(),
project.getArtifactId() + "-" + project.getVersion() + "-javadoc.jar");
if (javadocJar.exists()) {
projectHelper.attachArtifact(project, javadocJar, "jar", "javadoc");
}
// Add additional resource directory
projectHelper.addResource(project,
"src/main/config",
Arrays.asList("**/*.properties", "**/*.xml"),
Arrays.asList("**/test-*"));
}Interface for resolving project dependencies at various scopes.
public interface ProjectDependenciesResolver {
/**
* Resolve dependencies for a project.
*
* @param project the Maven project
* @param scopesToResolve dependency scopes to include
* @param session the Maven session
* @return dependency resolution result
* @throws DependencyResolutionException if resolution fails
*/
DependencyResolutionResult resolve(MavenProject project, Collection<String> scopesToResolve,
MavenSession session) throws DependencyResolutionException;
/**
* Resolve dependencies for a project with exclusion filters.
*/
DependencyResolutionResult resolve(MavenProject project, Collection<String> scopesToResolve,
Collection<String> scopesToCollect, MavenSession session) throws DependencyResolutionException;
}Dependency Resolution Example:
import org.apache.maven.ProjectDependenciesResolver;
import org.apache.maven.project.DependencyResolutionResult;
@Component
private ProjectDependenciesResolver dependencyResolver;
public void resolveDependencies(MavenProject project, MavenSession session) throws Exception {
// Resolve compile and runtime dependencies
Collection<String> scopesToResolve = Arrays.asList(
Artifact.SCOPE_COMPILE,
Artifact.SCOPE_RUNTIME,
Artifact.SCOPE_PROVIDED
);
DependencyResolutionResult result = dependencyResolver.resolve(
project, scopesToResolve, session);
// Process resolved dependencies
System.out.println("Resolved dependencies:");
for (Dependency dependency : result.getDependencies()) {
Artifact artifact = dependency.getArtifact();
System.out.println(" " + artifact.getGroupId() + ":" +
artifact.getArtifactId() + ":" + artifact.getVersion() +
" (scope: " + artifact.getScope() +
", file: " + artifact.getFile() + ")");
}
// Handle unresolved dependencies
if (!result.getUnresolvedDependencies().isEmpty()) {
System.err.println("Unresolved dependencies:");
for (Dependency unresolved : result.getUnresolvedDependencies()) {
System.err.println(" " + unresolved.getGroupId() + ":" +
unresolved.getArtifactId() + ":" + unresolved.getVersion());
}
}
// Handle collection errors
if (!result.getCollectionErrors().isEmpty()) {
System.err.println("Collection errors:");
for (Exception error : result.getCollectionErrors()) {
System.err.println(" " + error.getMessage());
}
}
}public interface DependencyResolutionResult {
List<Dependency> getDependencies();
List<Dependency> getUnresolvedDependencies();
List<Exception> getCollectionErrors();
DependencyNode getDependencyGraph();
}
public class DependencyResolutionRequiredException extends Exception {
public DependencyResolutionRequiredException(MavenProject project);
public MavenProject getProject();
}
public class ModelProblem {
public enum Severity {
FATAL, ERROR, WARNING
}
public String getMessage();
public Severity getSeverity();
public int getLineNumber();
public int getColumnNumber();
public String getSource();
}
public interface DependencyNode {
List<DependencyNode> getChildren();
Dependency getDependency();
DependencyNode getParent();
String getPremanagedScope();
String getPremanagedVersion();
Collection<Object> getContexts();
}
public interface Profile {
String getId();
Activation getActivation();
BuildBase getBuild();
List<Repository> getRepositories();
List<Repository> getPluginRepositories();
List<Dependency> getDependencies();
DependencyManagement getDependencyManagement();
Properties getProperties();
}
public interface Plugin {
String getGroupId();
String getArtifactId();
String getVersion();
String getExtensions();
List<PluginExecution> getExecutions();
List<Dependency> getDependencies();
Object getConfiguration();
}
public interface Build {
String getSourceDirectory();
String getScriptSourceDirectory();
String getTestSourceDirectory();
String getOutputDirectory();
String getTestOutputDirectory();
List<Extension> getExtensions();
String getDefaultGoal();
List<Resource> getResources();
List<Resource> getTestResources();
String getDirectory();
String getFinalName();
List<String> getFilters();
PluginManagement getPluginManagement();
List<Plugin> getPlugins();
}Install with Tessl CLI
npx tessl i tessl/maven-org-apache-maven--maven-core