0
# Project Management
1
2
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.
3
4
## Core Project Model
5
6
### MavenProject Class
7
8
The central representation of a Maven project, providing access to all project information including model, artifacts, dependencies, and build paths.
9
10
```java { .api }
11
public class MavenProject implements Cloneable {
12
/**
13
* Get the project's main artifact.
14
*/
15
public Artifact getArtifact();
16
17
/**
18
* Set the project's main artifact.
19
*/
20
public void setArtifact(Artifact artifact);
21
22
/**
23
* Get the project object model (POM).
24
*/
25
public Model getModel();
26
27
/**
28
* Set the project object model.
29
*/
30
public void setModel(Model model);
31
32
// Project Identity
33
public String getGroupId();
34
public String getArtifactId();
35
public String getVersion();
36
public String getName();
37
public String getDescription();
38
public String getUrl();
39
40
// Project Structure
41
public File getFile();
42
public File getBasedir();
43
public String getPackaging();
44
45
// Parent/Child Relationships
46
public MavenProject getParent();
47
public void setParent(MavenProject parent);
48
public List<MavenProject> getCollectedProjects();
49
public void setCollectedProjects(List<MavenProject> collectedProjects);
50
51
// Dependencies
52
public List<Dependency> getDependencies();
53
public List<Dependency> getCompileDependencies();
54
public List<Dependency> getTestDependencies();
55
public List<Dependency> getRuntimeDependencies();
56
57
// Dependency Management
58
public DependencyManagement getDependencyManagement();
59
public void setDependencyManagement(DependencyManagement dependencyManagement);
60
61
// Build Paths
62
public List<String> getCompileSourceRoots();
63
public List<String> getTestCompileSourceRoots();
64
public List<String> getCompileClasspathElements() throws DependencyResolutionRequiredException;
65
public List<String> getTestClasspathElements() throws DependencyResolutionRequiredException;
66
public List<String> getRuntimeClasspathElements() throws DependencyResolutionRequiredException;
67
public List<String> getSystemClasspathElements() throws DependencyResolutionRequiredException;
68
69
// Build Configuration
70
public Build getBuild();
71
public void setBuild(Build build);
72
73
// Properties
74
public Properties getProperties();
75
public void setProperties(Properties properties);
76
77
// Profiles
78
public List<Profile> getActiveProfiles();
79
public void setActiveProfiles(List<Profile> activeProfiles);
80
public List<String> getInjectedProfileIds();
81
82
// Artifacts
83
public Set<Artifact> getArtifacts();
84
public void setArtifacts(Set<Artifact> artifacts);
85
public Set<Artifact> getDependencyArtifacts();
86
public void setDependencyArtifacts(Set<Artifact> dependencyArtifacts);
87
88
// Attached Artifacts
89
public List<Artifact> getAttachedArtifacts();
90
public void addAttachedArtifact(Artifact artifact);
91
92
// Plugin Configuration
93
public List<Plugin> getBuildPlugins();
94
public Map<String, Plugin> getPluginMap();
95
public Plugin getPlugin(String pluginKey);
96
97
// Reporting
98
public List<ReportPlugin> getReportPlugins();
99
public Map<String, ReportPlugin> getReportPluginMap();
100
101
// Repositories
102
public List<Repository> getRepositories();
103
public List<Repository> getPluginRepositories();
104
105
// Project Context
106
public Object getContextValue(String key);
107
public void setContextValue(String key, Object value);
108
109
// Lifecycle
110
public void addLifecyclePhase(String lifecycle);
111
public Set<String> getLifecyclePhases();
112
}
113
```
114
115
**Basic Usage Example:**
116
```java
117
import org.apache.maven.project.MavenProject;
118
import org.apache.maven.model.Dependency;
119
120
public void analyzeProject(MavenProject project) throws Exception {
121
// Basic project information
122
System.out.println("Project: " + project.getGroupId() + ":" +
123
project.getArtifactId() + ":" + project.getVersion());
124
System.out.println("Name: " + project.getName());
125
System.out.println("Packaging: " + project.getPackaging());
126
System.out.println("Base Directory: " + project.getBasedir());
127
128
// Dependencies
129
System.out.println("Dependencies:");
130
for (Dependency dep : project.getDependencies()) {
131
System.out.println(" " + dep.getGroupId() + ":" +
132
dep.getArtifactId() + ":" + dep.getVersion() +
133
" (scope: " + dep.getScope() + ")");
134
}
135
136
// Source paths
137
System.out.println("Compile Source Roots:");
138
for (String sourceRoot : project.getCompileSourceRoots()) {
139
System.out.println(" " + sourceRoot);
140
}
141
142
// Classpath elements
143
System.out.println("Compile Classpath:");
144
for (String classpathElement : project.getCompileClasspathElements()) {
145
System.out.println(" " + classpathElement);
146
}
147
148
// Build plugins
149
System.out.println("Build Plugins:");
150
for (Plugin plugin : project.getBuildPlugins()) {
151
System.out.println(" " + plugin.getGroupId() + ":" +
152
plugin.getArtifactId() + ":" + plugin.getVersion());
153
}
154
}
155
```
156
157
## Project Building
158
159
### ProjectBuilder Interface
160
161
Primary interface for building Maven projects from POM files and other sources.
162
163
```java { .api }
164
public interface ProjectBuilder {
165
/**
166
* Build a single project from a POM file.
167
*
168
* @param projectFile the POM file to build from
169
* @param request build configuration and context
170
* @return project building result with built project
171
* @throws ProjectBuildingException if building fails
172
*/
173
ProjectBuildingResult build(File projectFile, ProjectBuildingRequest request)
174
throws ProjectBuildingException;
175
176
/**
177
* Build a project from an artifact coordinate.
178
*
179
* @param projectArtifact the artifact to build project for
180
* @param request build configuration and context
181
* @return project building result with built project
182
* @throws ProjectBuildingException if building fails
183
*/
184
ProjectBuildingResult build(Artifact projectArtifact, ProjectBuildingRequest request)
185
throws ProjectBuildingException;
186
187
/**
188
* Build projects from a list of POM files.
189
*
190
* @param projectFiles list of POM files to build
191
* @param recursive whether to include child modules
192
* @param request build configuration and context
193
* @return list of project building results
194
* @throws ProjectBuildingException if any build fails
195
*/
196
List<ProjectBuildingResult> build(List<File> projectFiles, boolean recursive,
197
ProjectBuildingRequest request) throws ProjectBuildingException;
198
}
199
```
200
201
### ProjectBuildingRequest Interface
202
203
```java { .api }
204
public interface ProjectBuildingRequest {
205
// Repository Configuration
206
ProjectBuildingRequest setLocalRepository(ArtifactRepository localRepository);
207
ArtifactRepository getLocalRepository();
208
209
ProjectBuildingRequest setRemoteRepositories(List<ArtifactRepository> remoteRepositories);
210
List<ArtifactRepository> getRemoteRepositories();
211
212
ProjectBuildingRequest setPluginArtifactRepositories(List<ArtifactRepository> pluginArtifactRepositories);
213
List<ArtifactRepository> getPluginArtifactRepositories();
214
215
// Repository Session
216
ProjectBuildingRequest setRepositorySession(RepositorySystemSession repositorySession);
217
RepositorySystemSession getRepositorySession();
218
219
// Processing Configuration
220
ProjectBuildingRequest setProcessPlugins(boolean processPlugins);
221
boolean isProcessPlugins();
222
223
ProjectBuildingRequest setResolveDependencies(boolean resolveDependencies);
224
boolean isResolveDependencies();
225
226
// Validation Configuration
227
ProjectBuildingRequest setValidationLevel(int validationLevel);
228
int getValidationLevel();
229
230
static final int VALIDATION_LEVEL_MINIMAL = 0;
231
static final int VALIDATION_LEVEL_MAVEN_2_0 = 20;
232
static final int VALIDATION_LEVEL_MAVEN_3_0 = 30;
233
static final int VALIDATION_LEVEL_MAVEN_3_1 = 31;
234
static final int VALIDATION_LEVEL_STRICT = 100;
235
236
// Profile Configuration
237
ProjectBuildingRequest setActiveProfileIds(List<String> activeProfileIds);
238
List<String> getActiveProfileIds();
239
240
ProjectBuildingRequest setInactiveProfileIds(List<String> inactiveProfileIds);
241
List<String> getInactiveProfileIds();
242
243
ProjectBuildingRequest setProfiles(List<Profile> profiles);
244
List<Profile> getProfiles();
245
246
// Properties
247
ProjectBuildingRequest setSystemProperties(Properties systemProperties);
248
Properties getSystemProperties();
249
250
ProjectBuildingRequest setUserProperties(Properties userProperties);
251
Properties getUserProperties();
252
253
// Build Start Time
254
ProjectBuildingRequest setBuildStartTime(Date buildStartTime);
255
Date getBuildStartTime();
256
}
257
```
258
259
### ProjectBuildingResult Interface
260
261
```java { .api }
262
public interface ProjectBuildingResult {
263
/**
264
* Get the project ID that was built.
265
*/
266
String getProjectId();
267
268
/**
269
* Get the POM file used for building.
270
*/
271
File getPomFile();
272
273
/**
274
* Get the built Maven project.
275
*/
276
MavenProject getProject();
277
278
/**
279
* Get any problems that occurred during building.
280
*/
281
List<ModelProblem> getProblems();
282
283
/**
284
* Get dependency resolution result if dependencies were resolved.
285
*/
286
DependencyResolutionResult getDependencyResolutionResult();
287
}
288
```
289
290
**Project Building Example:**
291
```java
292
import org.apache.maven.project.ProjectBuilder;
293
import org.apache.maven.project.ProjectBuildingRequest;
294
import org.apache.maven.project.ProjectBuildingResult;
295
import org.apache.maven.project.DefaultProjectBuildingRequest;
296
297
@Component
298
private ProjectBuilder projectBuilder;
299
300
@Component
301
private RepositorySystem repositorySystem;
302
303
public MavenProject buildProject(File pomFile) throws Exception {
304
// Create building request
305
ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
306
307
// Configure repository session
308
DefaultRepositorySystemSession repoSession = new DefaultRepositorySystemSession();
309
repoSession.setLocalRepositoryManager(
310
repositorySystem.newLocalRepositoryManager(repoSession, localRepo));
311
request.setRepositorySession(repoSession);
312
313
// Configure repositories
314
request.setLocalRepository(localRepo);
315
request.setRemoteRepositories(remoteRepos);
316
request.setPluginArtifactRepositories(pluginRepos);
317
318
// Configure processing options
319
request.setProcessPlugins(true);
320
request.setResolveDependencies(true);
321
request.setValidationLevel(ProjectBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1);
322
323
// Set properties
324
Properties userProps = new Properties();
325
userProps.setProperty("maven.compiler.source", "17");
326
userProps.setProperty("maven.compiler.target", "17");
327
request.setUserProperties(userProps);
328
329
// Build project
330
ProjectBuildingResult result = projectBuilder.build(pomFile, request);
331
332
// Check for problems
333
if (!result.getProblems().isEmpty()) {
334
System.out.println("Build problems:");
335
for (ModelProblem problem : result.getProblems()) {
336
System.out.println(" " + problem.getSeverity() + ": " + problem.getMessage());
337
}
338
}
339
340
return result.getProject();
341
}
342
343
// Build multiple projects
344
public List<MavenProject> buildMultiModuleProject(File rootPom) throws Exception {
345
ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
346
// ... configure request
347
348
List<ProjectBuildingResult> results = projectBuilder.build(
349
Arrays.asList(rootPom), true, request);
350
351
List<MavenProject> projects = new ArrayList<>();
352
for (ProjectBuildingResult result : results) {
353
projects.add(result.getProject());
354
}
355
356
return projects;
357
}
358
```
359
360
## Project Utilities
361
362
### MavenProjectHelper Interface
363
364
Utility interface for manipulating Maven projects and attached artifacts.
365
366
```java { .api }
367
public interface MavenProjectHelper {
368
/**
369
* Attach an artifact to the project.
370
*
371
* @param project the Maven project
372
* @param artifactFile the artifact file to attach
373
* @param artifactType the type of artifact (jar, war, etc.)
374
*/
375
void attachArtifact(MavenProject project, File artifactFile, String artifactType);
376
377
/**
378
* Attach an artifact with classifier.
379
*
380
* @param project the Maven project
381
* @param artifactFile the artifact file to attach
382
* @param artifactType the type of artifact
383
* @param artifactClassifier the classifier (sources, javadoc, etc.)
384
*/
385
void attachArtifact(MavenProject project, File artifactFile, String artifactType, String artifactClassifier);
386
387
/**
388
* Attach an existing artifact.
389
*
390
* @param project the Maven project
391
* @param artifact the artifact to attach
392
* @param artifactFile the file for the artifact
393
*/
394
void attachArtifact(MavenProject project, Artifact artifact, File artifactFile);
395
396
/**
397
* Add a resource directory to the project.
398
*
399
* @param project the Maven project
400
* @param resourceDirectory the resource directory to add
401
* @param includes list of include patterns (can be null)
402
* @param excludes list of exclude patterns (can be null)
403
*/
404
void addResource(MavenProject project, String resourceDirectory, List<String> includes, List<String> excludes);
405
406
/**
407
* Add a test resource directory to the project.
408
*/
409
void addTestResource(MavenProject project, String resourceDirectory, List<String> includes, List<String> excludes);
410
}
411
```
412
413
**Project Helper Usage:**
414
```java
415
import org.apache.maven.project.MavenProjectHelper;
416
417
@Component
418
private MavenProjectHelper projectHelper;
419
420
public void processArtifacts(MavenProject project) {
421
// Attach source JAR
422
File sourceJar = new File(project.getBuild().getDirectory(),
423
project.getArtifactId() + "-" + project.getVersion() + "-sources.jar");
424
if (sourceJar.exists()) {
425
projectHelper.attachArtifact(project, sourceJar, "jar", "sources");
426
}
427
428
// Attach Javadoc JAR
429
File javadocJar = new File(project.getBuild().getDirectory(),
430
project.getArtifactId() + "-" + project.getVersion() + "-javadoc.jar");
431
if (javadocJar.exists()) {
432
projectHelper.attachArtifact(project, javadocJar, "jar", "javadoc");
433
}
434
435
// Add additional resource directory
436
projectHelper.addResource(project,
437
"src/main/config",
438
Arrays.asList("**/*.properties", "**/*.xml"),
439
Arrays.asList("**/test-*"));
440
}
441
```
442
443
## Dependency Resolution
444
445
### ProjectDependenciesResolver Interface
446
447
Interface for resolving project dependencies at various scopes.
448
449
```java { .api }
450
public interface ProjectDependenciesResolver {
451
/**
452
* Resolve dependencies for a project.
453
*
454
* @param project the Maven project
455
* @param scopesToResolve dependency scopes to include
456
* @param session the Maven session
457
* @return dependency resolution result
458
* @throws DependencyResolutionException if resolution fails
459
*/
460
DependencyResolutionResult resolve(MavenProject project, Collection<String> scopesToResolve,
461
MavenSession session) throws DependencyResolutionException;
462
463
/**
464
* Resolve dependencies for a project with exclusion filters.
465
*/
466
DependencyResolutionResult resolve(MavenProject project, Collection<String> scopesToResolve,
467
Collection<String> scopesToCollect, MavenSession session) throws DependencyResolutionException;
468
}
469
```
470
471
**Dependency Resolution Example:**
472
```java
473
import org.apache.maven.ProjectDependenciesResolver;
474
import org.apache.maven.project.DependencyResolutionResult;
475
476
@Component
477
private ProjectDependenciesResolver dependencyResolver;
478
479
public void resolveDependencies(MavenProject project, MavenSession session) throws Exception {
480
// Resolve compile and runtime dependencies
481
Collection<String> scopesToResolve = Arrays.asList(
482
Artifact.SCOPE_COMPILE,
483
Artifact.SCOPE_RUNTIME,
484
Artifact.SCOPE_PROVIDED
485
);
486
487
DependencyResolutionResult result = dependencyResolver.resolve(
488
project, scopesToResolve, session);
489
490
// Process resolved dependencies
491
System.out.println("Resolved dependencies:");
492
for (Dependency dependency : result.getDependencies()) {
493
Artifact artifact = dependency.getArtifact();
494
System.out.println(" " + artifact.getGroupId() + ":" +
495
artifact.getArtifactId() + ":" + artifact.getVersion() +
496
" (scope: " + artifact.getScope() +
497
", file: " + artifact.getFile() + ")");
498
}
499
500
// Handle unresolved dependencies
501
if (!result.getUnresolvedDependencies().isEmpty()) {
502
System.err.println("Unresolved dependencies:");
503
for (Dependency unresolved : result.getUnresolvedDependencies()) {
504
System.err.println(" " + unresolved.getGroupId() + ":" +
505
unresolved.getArtifactId() + ":" + unresolved.getVersion());
506
}
507
}
508
509
// Handle collection errors
510
if (!result.getCollectionErrors().isEmpty()) {
511
System.err.println("Collection errors:");
512
for (Exception error : result.getCollectionErrors()) {
513
System.err.println(" " + error.getMessage());
514
}
515
}
516
}
517
```
518
519
## Types
520
521
```java { .api }
522
public interface DependencyResolutionResult {
523
List<Dependency> getDependencies();
524
List<Dependency> getUnresolvedDependencies();
525
List<Exception> getCollectionErrors();
526
DependencyNode getDependencyGraph();
527
}
528
529
public class DependencyResolutionRequiredException extends Exception {
530
public DependencyResolutionRequiredException(MavenProject project);
531
public MavenProject getProject();
532
}
533
534
public class ModelProblem {
535
public enum Severity {
536
FATAL, ERROR, WARNING
537
}
538
539
public String getMessage();
540
public Severity getSeverity();
541
public int getLineNumber();
542
public int getColumnNumber();
543
public String getSource();
544
}
545
546
public interface DependencyNode {
547
List<DependencyNode> getChildren();
548
Dependency getDependency();
549
DependencyNode getParent();
550
String getPremanagedScope();
551
String getPremanagedVersion();
552
Collection<Object> getContexts();
553
}
554
555
public interface Profile {
556
String getId();
557
Activation getActivation();
558
BuildBase getBuild();
559
List<Repository> getRepositories();
560
List<Repository> getPluginRepositories();
561
List<Dependency> getDependencies();
562
DependencyManagement getDependencyManagement();
563
Properties getProperties();
564
}
565
566
public interface Plugin {
567
String getGroupId();
568
String getArtifactId();
569
String getVersion();
570
String getExtensions();
571
List<PluginExecution> getExecutions();
572
List<Dependency> getDependencies();
573
Object getConfiguration();
574
}
575
576
public interface Build {
577
String getSourceDirectory();
578
String getScriptSourceDirectory();
579
String getTestSourceDirectory();
580
String getOutputDirectory();
581
String getTestOutputDirectory();
582
List<Extension> getExtensions();
583
String getDefaultGoal();
584
List<Resource> getResources();
585
List<Resource> getTestResources();
586
String getDirectory();
587
String getFinalName();
588
List<String> getFilters();
589
PluginManagement getPluginManagement();
590
List<Plugin> getPlugins();
591
}
592
```