### Installing/Deploying Artifacts Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Provides examples for installing artifacts to the local repository and deploying them to a remote repository. ```APIDOC ## Installing/Deploying Artifacts **Start here:** `org.apache.maven.api.Session#installArtifacts()` and `#deployArtifact()` ```java ProducedArtifact artifact = session.createProducedArtifact("com.example", "lib", "1.0", "jar"); session.setArtifactPath(artifact, Paths.get("target/lib.jar")); // Install to local repository session.installArtifacts(artifact); // Deploy to remote repository RemoteRepository repo = session.createRemoteRepository("myrepo", "https://repo.example.com"); session.deployArtifact(repo, artifact); ``` **Documentation:** See [session-and-core-types.md](session-and-core-types.md) ``` -------------------------------- ### Create and Install a Produced Artifact Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Demonstrates how to create a produced artifact and set its path for installation. ```java ProducedArtifact artifact = session.createProducedArtifact( "com.example", "mylib", "1.0.0", "jar" ); session.setArtifactPath(artifact, Paths.get("target/mylib.jar")); session.installArtifacts(artifact); ``` -------------------------------- ### Build and Install Maven Extension Source: https://github.com/apache/maven/blob/master/its/core-it-suite/src/test/resources/mng-8572-di-type-handler/README.md Commands to build and install the custom Maven extension plugin. ```bash cd extension mvn install ``` -------------------------------- ### Install Dummy Artifact Source: https://github.com/apache/maven/blob/master/its/core-it-suite/src/test/resources/mng-8572-di-type-handler/README.md Command to install the dummy artifact required for the test project. ```bash cd test ./install-dummy.sh ``` -------------------------------- ### Install and Deploy Artifacts Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Install an artifact to the local repository or deploy it to a remote repository. Requires creating `ProducedArtifact` and optionally `RemoteRepository`. ```java ProducedArtifact artifact = session.createProducedArtifact("com.example", "lib", "1.0", "jar"); session.setArtifactPath(artifact, Paths.get("target/lib.jar")); // Install to local repository session.installArtifacts(artifact); // Deploy to remote repository RemoteRepository repo = session.createRemoteRepository("myrepo", "https://repo.example.com"); session.deployArtifact(repo, artifact); ``` -------------------------------- ### Maven Dependency Coordinate Examples Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Provides concrete examples of Maven dependency coordinates in the standard format. ```text org.apache.maven:maven-core:4.0.0 ``` ```text org.junit:junit:jar:sources:4.13.2 ``` ```text log4j:log4j:1.2.17:jar ``` -------------------------------- ### Bootstrap Apache Maven Source: https://github.com/apache/maven/blob/master/README.md Command to build and install the Maven distribution to a specified directory. Requires Java 17+ and an existing Maven 3.9.0+ installation. ```bash mvn -DdistributionTargetDir="$HOME/app/maven/apache-maven-4.1.x-SNAPSHOT" clean package ``` -------------------------------- ### Version Range Syntax Examples Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Illustrates various syntaxes for defining version ranges in Maven. ```text All versions ``` ```text Exactly 1.0 ``` ```text Exactly 1.0 ``` ```text 1.2 ≤ x ≤ 1.3 ``` ```text 1.2 ≤ x < 1.3 ``` ```text x ≥ 1.2 ``` ```text x ≤ 1.3 ``` -------------------------------- ### Complete Request/Response Example Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Demonstrates the typical request/response pattern for various Maven services. ```APIDOC ## Complete Request/Response Example ### Description This example illustrates how to use Maven services like ArtifactResolver, DependencyResolver, and ProjectBuilder, showcasing the pattern of obtaining a service, building a request, executing the service, and processing the result. ### Code Example ```java import org.apache.maven.api.*; import org.apache.maven.api.services.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; public class ServicePatternExample { public static void main(String[] args) throws Exception { Session session = // ... obtain from Maven runtime // Example 1: Resolve Artifact { ArtifactResolver resolver = session.getService(ArtifactResolver.class); ArtifactCoordinates coords = session.createArtifactCoordinates( "org.apache.maven:maven-core:4.0.0" ); // Build request ArtifactResolverRequest req = ArtifactResolverRequest.build(session, java.util.Collections.singletonList(coords)); // Execute ArtifactResolverResult result = resolver.resolve(req); // Process for (DownloadedArtifact artifact : result.getArtifacts()) { System.out.println("Artifact: " + artifact + " at " + artifact.getPath()); } } // Example 2: Collect Dependencies { DependencyResolver depResolver = session.getService(DependencyResolver.class); Artifact artifact = session.createArtifact( "org.apache.maven", "maven-core", "4.0.0", "jar" ); PathScope scope = session.requirePathScope("compile"); // Build request DependencyResolverRequest req = DependencyResolverRequest.build(session, artifact) .scope(scope); // Execute Node graph = depResolver.collect(req); // Process System.out.println("Root: " + graph.getArtifact()); for (Node child : graph.getChildren()) { System.out.println(" Dependency: " + child.getArtifact()); } } // Example 3: Build Project { ProjectBuilder builder = session.getService(ProjectBuilder.class); // Build request ProjectBuilderRequest req = ProjectBuilderRequest.build(session) .pomPath(Paths.get("pom.xml")); // Execute ProjectBuilderResult result = builder.build(req); // Process Project project = result.getProject(); System.out.println("Project: " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()); for (BuilderProblem problem : result.getProblems()) { System.out.println(" Problem: " + problem.getMessage()); } } } } ``` ``` -------------------------------- ### Install Artifacts Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Installs artifacts to the local Maven repository. This method takes a collection of `ProducedArtifact` objects and may throw an `ArtifactInstallerException` if the installation fails. Ensure the artifact path is set before calling this method. ```java void installArtifacts(@Nonnull Collection artifacts) ``` ```java ProducedArtifact artifact = session.createProducedArtifact( "com.example", "mylib", "1.0.0", "jar" ); session.setArtifactPath(artifact, Paths.get("/path/to/mylib.jar")); session.installArtifacts(artifact); ``` -------------------------------- ### Install Artifacts with ArtifactInstaller Source: https://github.com/apache/maven/blob/master/_autodocs/core-services-api.md Use this service to install produced artifacts into the local Maven repository. Ensure you have a valid Maven session and a collection of produced artifacts. ```java void install( @Nonnull Session session, @Nonnull Collection artifacts ) ``` ```java ArtifactInstaller installer = session.getService(ArtifactInstaller.class); ProducedArtifact artifact = session.createProducedArtifact( "com.example", "mylib", "1.0.0", "jar" ); session.setArtifactPath(artifact, Paths.get("/path/to/mylib.jar")); installer.install(session, Arrays.asList(artifact)); ``` -------------------------------- ### Get Maven Installation Directory Source: https://github.com/apache/maven/blob/master/_autodocs/cli-invoker-api.md Retrieve the path to the Maven installation directory, typically derived from the 'maven.home' system property. ```java Path mavenHome = invokerRequest.installationDirectory(); Path libDir = mavenHome.resolve("lib"); ``` -------------------------------- ### Iterate Through Project Source Roots Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Example demonstrating how to iterate through a project's source roots and print their paths. ```java for (SourceRoot src : project.getSourceRoots()) { System.out.println("Source: " + src.getPath()); } ``` -------------------------------- ### installArtifacts Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Installs artifacts to the local repository. ```APIDOC ## installArtifacts(Collection) ### Description Installs artifacts to the local repository. ### Method APIDOC ### Parameters #### Path Parameters - **artifacts** (Collection) - Required - The artifacts to install ### Throws - **ArtifactInstallerException** - If the artifacts installation failed ### Request Example ```java ProducedArtifact artifact = session.createProducedArtifact( "com.example", "mylib", "1.0.0", "jar" ); session.setArtifactPath(artifact, Paths.get("/path/to/mylib.jar")); session.installArtifacts(artifact); ``` ``` -------------------------------- ### Get Parser Request Arguments Source: https://github.com/apache/maven/blob/master/_autodocs/cli-invoker-api.md Retrieves the list of command-line arguments to be parsed. These are typically strings like "clean", "install", or flags like "-DskipTests". ```java @Nonnull List arguments() ``` -------------------------------- ### Build Maven Extension Source: https://github.com/apache/maven/blob/master/its/core-it-suite/src/test/resources/mng-8461/extension/README.md Execute this command to build the Maven extension locally. Ensure you have Maven wrapper installed. ```bash ./mvnw clean install ``` -------------------------------- ### ArtifactInstaller.install Source: https://github.com/apache/maven/blob/master/_autodocs/core-services-api.md Installs produced artifacts to the local Maven repository. This method is part of the ArtifactInstaller service. ```APIDOC ## install(Session, Collection) ### Description Installs produced artifacts to the local repository. ### Method `void install(Session session, Collection artifacts)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **session** (Session) - Required - The Maven session - **artifacts** (Collection) - Required - Artifacts to install ### Request Example ```java ArtifactInstaller installer = session.getService(ArtifactInstaller.class); ProducedArtifact artifact = session.createProducedArtifact( "com.example", "mylib", "1.0.0", "jar" ); session.setArtifactPath(artifact, Paths.get("/path/to/mylib.jar")); installer.install(session, Arrays.asList(artifact)); ``` ### Response #### Success Response (200) void #### Response Example None ``` -------------------------------- ### Example: Building ArtifactResolverRequest with Custom Repositories Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Demonstrates how to build an ArtifactResolverRequest using custom remote repositories. This involves creating a list of repositories and passing it to the builder. ```java List repos = Arrays.asList( session.createRemoteRepository("central", "https://repo.maven.apache.org/maven2") ); ArtifactResolverRequest request = ArtifactResolverRequest.build(session, coords) .repositories(repos); ``` -------------------------------- ### Parse and Get Version Range Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Demonstrates parsing a version constraint string and retrieving the resulting VersionRange object. ```java VersionConstraint constraint = session.parseVersionConstraint("[1.0,2.0)"); VersionRange range = constraint.getRange(); ``` -------------------------------- ### Develop Maven Plugin Mojo Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Example of a basic Maven plugin `Mojo` implementation. Annotations like `@Mojo` and `@Parameter` are used for configuration. ```java @Mojo( name = "mygoal", defaultPhase = "process-resources" ) public class MyMojo implements Mojo { @Parameter private File outputDirectory; private Log log; @Override public void execute() throws Exception { log.info("Executing my goal"); } } ``` -------------------------------- ### Register a Maven Build Event Listener Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Illustrates how to create and register a listener to receive build events, such as build start notifications. ```java Listener listener = event -> { if (event.getType() == EventType.BUILD_STARTED) { System.out.println("Build started!"); } }; session.registerListener(listener); ``` -------------------------------- ### Create ArtifactInstallerRequest Builder Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Creates a builder for installing artifacts to the local repository. Requires a session and a collection of produced artifacts. ```java static Builder build( Session session, Collection artifacts ) ``` -------------------------------- ### Resolve Artifact Example Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Shows how to use the ArtifactResolver service to resolve a specific artifact. It includes building the request with artifact coordinates and processing the results. ```java import org.apache.maven.api.*; import org.apache.maven.api.services.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; public class ServicePatternExample { public static void main(String[] args) throws Exception { Session session = // ... obtain from Maven runtime // Example 1: Resolve Artifact { ArtifactResolver resolver = session.getService(ArtifactResolver.class); ArtifactCoordinates coords = session.createArtifactCoordinates( "org.apache.maven:maven-core:4.0.0" ); // Build request ArtifactResolverRequest req = ArtifactResolverRequest.build(session, java.util.Collections.singletonList(coords)); // Execute ArtifactResolverResult result = resolver.resolve(req); // Process for (DownloadedArtifact artifact : result.getArtifacts()) { System.out.println("Artifact: " + artifact + " at " + artifact.getPath()); } } // Example 2: Collect Dependencies { DependencyResolver depResolver = session.getService(DependencyResolver.class); Artifact artifact = session.createArtifact( "org.apache.maven", "maven-core", "4.0.0", "jar" ); PathScope scope = session.requirePathScope("compile"); // Build request DependencyResolverRequest req = DependencyResolverRequest.build(session, artifact) .scope(scope); // Execute Node graph = depResolver.collect(req); // Process System.out.println("Root: " + graph.getArtifact()); for (Node child : graph.getChildren()) { System.out.println(" Dependency: " + child.getArtifact()); } } // Example 3: Build Project { ProjectBuilder builder = session.getService(ProjectBuilder.class); // Build request ProjectBuilderRequest req = ProjectBuilderRequest.build(session) .pomPath(Paths.get("pom.xml")); // Execute ProjectBuilderResult result = builder.build(req); // Process Project project = result.getProject(); System.out.println("Project: " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()); for (BuilderProblem problem : result.getProblems()) { System.out.println(" Problem: " + problem.getMessage()); } } } } ``` -------------------------------- ### Maven 4.0.0-beta-5 Dependency Tree Output Source: https://github.com/apache/maven/blob/master/its/core-it-suite/src/test/resources/mng-8347-transitive-dependency-manager/README.md Example output showing transitive dependency management behavior in Maven 4.0.0-beta-5. ```text $ mvn -V eu.maveniverse.maven.plugins:toolbox:tree -Dmaven.repo.local.tail=local-repo Apache Maven 4.0.0-beta-5 (6e78fcf6f5e76422c0eb358cd11f0c231ecafbad) Maven home: /home/cstamas/.sdkman/candidates/maven/4.0.0-beta-5 Java version: 21.0.4, vendor: Eclipse Adoptium, runtime: /home/cstamas/.sdkman/candidates/java/21.0.4-tem Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "6.11.4-201.fc40.x86_64", arch: "amd64", family: "unix" [WARNING] Unable to find the root directory. Create a .mvn directory in the root directory or add the root="true" attribute on the root project's model to identify it. [WARNING] Pre-Maven 4 legacy encrypted password detected for server my-legacy-server - configure password encryption with the help of mvnenc to be compatible with Maven 4. [WARNING] Pre-Maven 4 legacy encrypted password detected for server my-legacy-broken-server - configure password encryption with the help of mvnenc to be compatible with Maven 4. [INFO] Scanning for projects... [INFO] [INFO] ----------------------------------------< org.apache.maven.it.mresolver614:root >----------------------------------------- [INFO] Building root 1.0.0 [INFO] from pom.xml [INFO] ---------------------------------------------------------[ jar ]---------------------------------------------------------- [INFO] [INFO] --- toolbox:0.3.5:tree (default-cli) @ root --- [INFO] org.apache.maven.it.mresolver614:root:jar:1.0.0 [INFO] ╰─org.apache.maven.it.mresolver614:level1:jar:1.0.0 [compile] [INFO] ╰─org.apache.maven.it.mresolver614:level2:jar:1.0.0 [compile] [INFO] ╰─org.apache.maven.it.mresolver614:level3:jar:1.0.1 [compile] (version managed from 1.0.0) [INFO] ╰─org.apache.maven.it.mresolver614:level4:jar:1.0.1 [compile] (version managed from 1.0.0) [INFO] ╰─org.apache.maven.it.mresolver614:level5:jar:1.0.2 [compile] (version managed from 1.0.0) [INFO] ╰─org.apache.maven.it.mresolver614:level6:jar:1.0.2 [compile] (version managed from 1.0.0) [INFO] -------------------------------------------------------------------------------------------------------------------------- [INFO] BUILD SUCCESS [INFO] -------------------------------------------------------------------------------------------------------------------------- [INFO] Total time: 0.285 s [INFO] Finished at: 2024-10-24T19:21:10+02:00 ``` -------------------------------- ### Core Services API Source: https://github.com/apache/maven/blob/master/_autodocs/CONTENTS.txt Documentation for all Maven services, including ArtifactResolver, DependencyResolver, ProjectBuilder, and VersionResolver, with complete working examples. ```APIDOC ## Core Services API ### Description This section documents all core Maven services, providing detailed information on interfaces like `ArtifactResolver`, `DependencyResolver`, `ProjectBuilder`, and `VersionResolver`. It includes service exception hierarchies and complete working examples. ### Documented Services - `ArtifactResolver` - `DependencyResolver` - `ProjectBuilder` - `ModelBuilder` - `VersionResolver` - `VersionRangeResolver` - `RepositoryFactory` and registries ### Examples Complete working examples are provided for each service. ``` -------------------------------- ### Get Language ID Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Retrieves the identifier for a programming language. For example, 'java', 'groovy', or 'scala'. ```java Language java = session.requireLanguage("java"); String id = java.id(); // Returns "java" ``` -------------------------------- ### Get Packaging Language Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Retrieves the programming language associated with a project's packaging. For example, Java. ```java Language lang = project.getPackaging().language(); System.out.println("Project language: " + lang); ``` -------------------------------- ### Maven 3.9.9 Dependency Tree Output Source: https://github.com/apache/maven/blob/master/its/core-it-suite/src/test/resources/mng-8347-transitive-dependency-manager/README.md Example output showing non-transitive dependency management behavior in Maven 3.9.9. ```text $ mvn -V eu.maveniverse.maven.plugins:toolbox:tree -Dmaven.repo.local.tail=local-repo Apache Maven 3.9.9 (8e8579a9e76f7d015ee5ec7bfcdc97d260186937) Maven home: /home/cstamas/.sdkman/candidates/maven/3.9.9 Java version: 21.0.4, vendor: Eclipse Adoptium, runtime: /home/cstamas/.sdkman/candidates/java/21.0.4-tem Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "6.11.4-201.fc40.x86_64", arch: "amd64", family: "unix" [INFO] Scanning for projects... [INFO] [INFO] ---------------< org.apache.maven.it.mresolver614:root >---------------- [INFO] Building root 1.0.0 [INFO] from pom.xml [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- toolbox:0.3.5:tree (default-cli) @ root --- [INFO] org.apache.maven.it.mresolver614:root:jar:1.0.0 [INFO] ╰─org.apache.maven.it.mresolver614:level1:jar:1.0.0 [compile] [INFO] ╰─org.apache.maven.it.mresolver614:level2:jar:1.0.0 [compile] [INFO] ╰─org.apache.maven.it.mresolver614:level3:jar:1.0.0 [compile] [INFO] ╰─org.apache.maven.it.mresolver614:level4:jar:1.0.0 [compile] [INFO] ╰─org.apache.maven.it.mresolver614:level5:jar:1.0.0 [compile] [INFO] ╰─org.apache.maven.it.mresolver614:level6:jar:1.0.2 [compile] (version managed from 1.0.0) [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.192 s [INFO] Finished at: 2024-10-24T19:20:39+02:00 [INFO] ------------------------------------------------------------------------ $ ``` -------------------------------- ### Get Packaging ID Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Retrieves the identifier for a project's packaging type. For example, 'jar', 'war', or 'pom'. ```java Packaging packaging = project.getPackaging(); String id = packaging.id(); // Returns "jar", "war", "pom", etc. ``` -------------------------------- ### Using Maven as a Library Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Demonstrates how to use Maven as a library by creating an invoker, parsing an invocation request, and executing it. ```APIDOC ## Using Maven as a Library **Start here:** `org.apache.maven.api.cli.Invoker` ```java // Create invoker Invoker invoker = Tools.createInvoker(lookup, classLoader); // Parse and execute Parser parser = Tools.createParser(lookup, classLoader); InvokerRequest request = parser.parseInvocation(parseRequest); int exitCode = invoker.invoke(request); ``` **Documentation:** See [cli-invoker-api.md](cli-invoker-api.md) ``` -------------------------------- ### Building Projects Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Demonstrates how to build a Maven project using the ProjectBuilder service. ```APIDOC ## Building Projects **Start here:** `org.apache.maven.api.services.ProjectBuilder` ```java ProjectBuilder builder = session.getService(ProjectBuilder.class); ProjectBuilderRequest req = ProjectBuilderRequest.build(session) .pomPath(Paths.get("pom.xml")); Project project = builder.build(req).getProject(); ``` **Documentation:** See [core-services-api.md](core-services-api.md) ``` -------------------------------- ### ArtifactInstallerRequest.Builder.build Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Creates a builder for artifact installation. This method is used to initiate the process of installing artifacts to the local Maven repository. ```APIDOC ## ArtifactInstallerRequest.Builder.build ### Description Creates a builder for artifact installation. This method is used to initiate the process of installing artifacts to the local Maven repository. ### Method Signature ```java static Builder build( Session session, Collection artifacts ) ``` ### Parameters - **session** (Session) - Required - The current Maven session. - **artifacts** (Collection) - Required - The collection of artifacts to be installed. ### Returns `ArtifactInstallerRequest.Builder` - A builder instance for creating the artifact installer request. ``` -------------------------------- ### Get Degree of Concurrency Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Get the configured degree of concurrency for the build, indicating the number of threads Maven will use for parallel execution. ```java int threads = session.getDegreeOfConcurrency(); System.out.println("Build will use " + threads + " threads"); ``` -------------------------------- ### Get Multi-Module Project Directory Source: https://github.com/apache/maven/blob/master/_autodocs/cli-invoker-api.md Returns the multi-module project directory if it was specified, typically via the `-Dbasedir` option. Returns an empty Optional if not specified. ```java @Nonnull Optional multiModuleProjectDirectory() ``` -------------------------------- ### Accessing Maven Services Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Demonstrates the standard pattern for accessing and executing Maven services. This involves retrieving a service from the session, building a request with parameters, executing the service, and processing the results. ```java // 1. Get the service from session ServiceInterface service = session.getService(ServiceInterface.class); // 2. Build a request ServiceRequest request = ServiceRequest.build(session) .parameter1(value1) .parameter2(value2); // 3. Execute the service ServiceResult result = service.execute(request); // 4. Process results result.getArtifacts(); // or getProject(), getModel(), etc. ``` -------------------------------- ### Implement a Simple Mojo Source: https://github.com/apache/maven/blob/master/_autodocs/plugin-mojo-api.md Provides a basic implementation of the `Mojo` interface. Annotations are used to configure the Mojo's name, default phase, and parameters. ```java import org.apache.maven.api.plugin.Mojo; import org.apache.maven.api.plugin.Log; @org.apache.maven.api.plugin.annotations.Mojo( name = "greet", defaultPhase = "validate" ) public class GreetMojo implements Mojo { @org.apache.maven.api.plugin.annotations.Parameter( defaultValue = "World" ) private String name; private Log log; @Override public void execute() throws Exception { log.info("Hello, " + name + "!"); } } ``` -------------------------------- ### Complete Maven Plugin Mojo Example Source: https://github.com/apache/maven/blob/master/_autodocs/plugin-mojo-api.md This Java code defines a complete Maven plugin Mojo that generates documentation. It includes parameter injection for source and output directories, logging, file processing, and optional HTML generation. Use this as a template for creating custom Maven plugins. ```java package com.example.maven; import org.apache.maven.api.plugin.Mojo; import org.apache.maven.api.plugin.Log; import org.apache.maven.api.plugin.MojoException; import org.apache.maven.api.plugin.annotations.*; import org.apache.maven.api.Project; import org.apache.maven.api.Session; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Generates project documentation from source code. */ @Mojo( name = "generate-docs", defaultPhase = "prepare-package", requiresDependencyResolution = "compile" ) public class GenerateDocsMojo implements Mojo { /** * The Maven session. */ @Parameter(readonly = true) private Session session; /** * The current project. */ @Parameter(readonly = true) private Project project; /** * Output directory for generated documentation. */ @Parameter( defaultValue = "${project.basedir}/target/docs", required = true ) private File outputDirectory; /** * Source directory containing documentation sources. */ @Parameter( defaultValue = "${project.basedir}/src/docs", required = true ) private File sourceDirectory; /** * Whether to generate HTML output. */ @Parameter( property = "generateHtml", defaultValue = "true" ) private boolean generateHtml; /** * Logging instance provided by Maven. */ private Log log; @Override public void execute() throws Exception { // Validate parameters if (!sourceDirectory.exists()) { throw new MojoException( "Source directory does not exist: " + sourceDirectory ); } log.info("Generating documentation from: " + sourceDirectory); log.info("Output directory: " + outputDirectory); // Create output directory Path outPath = outputDirectory.toPath(); Files.createDirectories(outPath); // Process documentation files int processedCount = 0; Path sourcePath = sourceDirectory.toPath(); try { processedCount = Files.list(sourcePath) .filter(p -> p.toString().endsWith(".md")) .peek(p -> { try { processDocFile(p, outPath); } catch (Exception e) { log.warn("Failed to process " + p, e); } }) .mapToInt(p -> 1) .sum(); } catch (Exception e) { throw new MojoException("Documentation generation failed", e); } log.info("Successfully processed " + processedCount + " documentation files"); if (generateHtml) { log.info("Generating HTML output..."); generateHtmlOutput(outPath); } } private void processDocFile(Path sourcePath, Path outputPath) throws Exception { String filename = sourcePath.getFileName().toString(); Path targetPath = outputPath.resolve(filename); log.debug("Processing: " + sourcePath + " -> " + targetPath); // Process the file (simplified) Files.copy(sourcePath, targetPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING); } private void generateHtmlOutput(Path outputPath) throws Exception { log.info("HTML generation logic would go here"); // Generate HTML files from documentation Path htmlPath = outputPath.resolve("index.html"); Files.write(htmlPath, "Documentation".getBytes()); log.info("Generated HTML at: " + htmlPath); } } ``` -------------------------------- ### Get current monotonic clock time in nanoseconds Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Use this to get the current time from a monotonic clock, useful for measuring elapsed time. Obtain the MonotonicClock service from the session. ```java MonotonicClock clock = session.getService(MonotonicClock.class); long start = clock.now(); // ... do work long elapsed = clock.now() - start; ``` -------------------------------- ### Build Maven Core and Run Integration Tests Script Source: https://github.com/apache/maven/blob/master/its/README.md Build Maven core using the `-PversionlessMavenDist` profile, then execute the integration tests using the provided shell script. ```bash sh ./run-its.sh ``` -------------------------------- ### Develop a Maven Plugin with Mojo Interface Source: https://github.com/apache/maven/blob/master/_autodocs/README.md Shows the basic structure for creating a Maven plugin goal by implementing the `Mojo` interface. Use `@Parameter` for configuration and `Log` for output. Ensure proper exception handling with `MojoException`. ```java @Mojo(name = "mygoal", defaultPhase = "process-resources") public class MyMojo implements Mojo { @Parameter(required = true) private File outputDirectory; private Log log; @Override public void execute() throws Exception { log.info("Executing my goal"); } } ``` -------------------------------- ### Get Toolchains from ToolchainsBuilderResult Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves the collection of configured toolchains from the ToolchainsBuilderResult. ```java Collection getToolchains() ``` -------------------------------- ### Get Settings from SettingsBuilderResult Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves the effective Maven settings from the SettingsBuilderResult. ```java Settings getSettings() ``` -------------------------------- ### Get Event Timestamp Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Retrieves the timestamp of a Maven execution event. ```java long getTimestamp() ``` -------------------------------- ### Resource Management with Try-with-Resources Source: https://github.com/apache/maven/blob/master/_autodocs/api-index.md Demonstrates the use of try-with-resources for safe management of the Invoker resource. Ensure to handle potential InvokerExceptions. ```java try (Invoker invoker = Tools.createInvoker(lookup, cl)) { // Use invoker } catch (InvokerException e) { // Handle error } ``` -------------------------------- ### Get Event Type Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Retrieves the type of a Maven execution event. ```java EventType getType() ``` -------------------------------- ### Run Maven initialization commands Source: https://github.com/apache/maven/blob/master/its/core-it-suite/src/test/resources/mng-2339/b/readme.txt Execute these commands to verify that the -Dversion property overrides the POM version definition. ```bash mvn clean initialize ``` ```bash mvn -Dversion=2 clean initialize ``` -------------------------------- ### Get Project Version Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Retrieves the version string of the Maven project. ```java String getVersion() ``` -------------------------------- ### ProducedArtifact Interface Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Represents an artifact produced by the current build, which can be installed or deployed. ```APIDOC ## ProducedArtifact Interface Represents artifacts created during the build that can be installed or deployed. **Package:** `org.apache.maven.api` **Extends:** `Artifact` **Example:** ```java ProducedArtifact artifact = session.createProducedArtifact( "com.example", "mylib", "1.0.0", "jar" ); session.setArtifactPath(artifact, Paths.get("target/mylib.jar")); session.installArtifacts(artifact); ``` ``` -------------------------------- ### Create Local Repository Instance Source: https://github.com/apache/maven/blob/master/_autodocs/core-services-api.md Use this method to create a local repository instance for a given file system path. Ensure the path is valid. ```java RepositoryFactory factory = session.getService(RepositoryFactory.class); LocalRepository local = factory.createLocal(Paths.get("/home/user/.m2/repository")); ``` -------------------------------- ### Get Mojo Execution Phase Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Retrieves the lifecycle phase for a Mojo execution. ```java String getPhase() ``` -------------------------------- ### Lookup Service Instance Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Demonstrates how to obtain a service instance from the Maven session using its class type. Ensure the service interface is available and correctly typed. ```java T lookup(Class type) ``` -------------------------------- ### Run Maven Integration Tests in Docker Source: https://github.com/apache/maven/blob/master/its/environments/README.md Commands to build a Docker image, run it interactively, clone the Maven repository, and execute integration tests. Ensure the Maven distribution path is correctly set. ```bash $ID=$(docker build -q .) docker run --rm -t -i $ID bash $cd $HOME git clone https://gitbox.apache.org/repos/asf/maven.git ( cd maven && mvn clean verify ) git clone https://gitbox.apache.org/repos/asf/maven-integration-testing.git ( cd maven-integration-testing && mvn clean install -Prun-its -Dmaven.repo.local=$HOME/work/repo -DmavenDistro=$HOME/maven/apache-maven/target/apache-maven-...-bin.zip ) ``` -------------------------------- ### Get Mojo Execution Goal Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Retrieves the goal name for a Mojo execution. ```java String getGoal() ``` -------------------------------- ### Get Model Problem Exception Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves the exception that caused the model building problem, if any. ```java Exception getException() ``` -------------------------------- ### Accessing Maven Services via Session Source: https://github.com/apache/maven/blob/master/_autodocs/core-services-api.md Demonstrates how to obtain service instances like ArtifactResolver, DependencyResolver, and ProjectBuilder from the Maven session. Ensure the session object is available. ```java ArtifactResolver resolver = session.getService(ArtifactResolver.class); DependencyResolver depResolver = session.getService(DependencyResolver.class); ProjectBuilder builder = session.getService(ProjectBuilder.class); ``` -------------------------------- ### Get Project Artifact ID Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Retrieves the unique artifact identifier for the Maven project. ```java String getArtifactId() ``` -------------------------------- ### Get Project Group ID Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Retrieves the unique group identifier for the Maven project. ```java String getGroupId() ``` -------------------------------- ### Run Maven Integration Tests with Vagrant Source: https://github.com/apache/maven/blob/master/its/environments/README.md Commands for Vagrant environments to SSH into a machine, clone the Maven repository, and execute integration tests. This is for non-Linux systems and requires a Vagrant provider like Virtualbox. ```bash $vagrant ssh $git clone https://gitbox.apache.org/repos/asf/maven.git ( cd maven && mvn clean verify ) $git clone https://gitbox.apache.org/repos/asf/maven-integration-testing.git ( cd maven-integration-testing && mvn clean install -Prun-its -Dmaven.repo.local=$HOME/work/repo -DmavenDistro=$HOME/maven/apache-maven/target/apache-maven-...-bin.zip ) ``` -------------------------------- ### Get Model Problem Message Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves the error message associated with a model building problem. ```java String getMessage() ``` -------------------------------- ### Build Project and Resolve Dependencies with Maven API Source: https://github.com/apache/maven/blob/master/_autodocs/core-services-api.md This Java snippet shows how to obtain a Maven session, build a project from a pom.xml, collect its dependency graph, and resolve the dependencies to concrete file paths. Ensure a Maven runtime session is available. ```java import org.apache.maven.api.*; import org.apache.maven.api.services.*; import java.nio.file.Paths; import java.util.*; public class ServiceExample { public static void main(String[] args) throws Exception { Session session = // ... obtain from Maven runtime // 1. Build a project ProjectBuilder builder = session.getService(ProjectBuilder.class); ProjectBuilderRequest projectReq = ProjectBuilderRequest.build(session) .pomPath(Paths.get("pom.xml")); Project project = builder.build(projectReq).getProject(); System.out.println("Built project: " + project); // 2. Collect dependencies DependencyResolver depResolver = session.getService(DependencyResolver.class); Artifact artifact = project.getMainArtifact() .orElseThrow(() -> new Exception("No main artifact")); PathScope scope = session.requirePathScope("compile"); Node depGraph = depResolver.collect( DependencyResolverRequest.build(session, artifact) .scope(scope) ); // 3. Resolve to concrete paths DependencyResolverResult result = depResolver.resolve( DependencyResolverRequest.build(session, artifact) .scope(scope) ); List classpath = result.getPaths(); System.out.println("Classpath entries: " + classpath.size()); for (Path p : classpath) { System.out.println(" - " + p); } } } ``` -------------------------------- ### Get Dependency Graph Root Node Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves the root node of the dependency graph from a DependencyResolverResult. ```java Node getRoot() ``` -------------------------------- ### Get Project POM Artifact Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Retrieves the project's POM artifact, which is guaranteed to be present. ```java ProducedArtifact getPomArtifact() ``` -------------------------------- ### Advanced benchmark options Source: https://github.com/apache/maven/blob/master/impl/maven-xml/BENCHMARKS.md Commands for generating JSON reports and profiling memory or execution using async profiler. ```bash mvn test-compile exec:java -Dexec.mainClass="org.openjdk.jmh.Main" \ -Dexec.classpathScope=test \ -Dexec.args="-rf json -rff benchmark-results.json org.apache.maven.internal.xml.*Benchmark" \ -pl impl/maven-xml ``` ```bash mvn test-compile exec:java -Dexec.mainClass="org.openjdk.jmh.Main" \ -Dexec.classpathScope=test \ -Dexec.args="-prof gc XmlPlexusConfigurationMemoryBenchmark" \ -pl impl/maven-xml ``` ```bash mvn test-compile exec:java -Dexec.mainClass="org.openjdk.jmh.Main" \ -Dexec.classpathScope=test \ -Dexec.args="-prof async:output=flamegraph XmlPlexusConfigurationBenchmark" \ -pl impl/maven-xml ``` -------------------------------- ### Get Artifact ID Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Retrieves the artifact identifier. This uniquely identifies the artifact within its group. ```java @Nonnull String getArtifactId() ``` -------------------------------- ### Iterate and Print Model Problems Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Example of iterating through a collection of model problems and printing their severity and message. ```java for (BuilderProblem problem : result.getProblems()) { System.out.println(problem.getSeverity() + ": " + problem.getMessage()); } ``` -------------------------------- ### Build Request with Parameters Source: https://github.com/apache/maven/blob/master/_autodocs/README.md Demonstrates how to construct a request object with parameters using the Request.build() method. This pattern is used for interacting with Maven services. ```java Request req = Request.build(session) .parameter1(value1) .parameter2(value2); Result result = service.execute(req); ``` -------------------------------- ### Configure Project Builder with Model Source Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Allows setting a model source directly, bypassing the need for a file path. Returns the builder instance. ```java Builder modelSource(ModelSource modelSource) ``` -------------------------------- ### Get Model Problem Severity Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves the severity level (WARNING or ERROR) of a model building problem. ```java Severity getSeverity() ``` -------------------------------- ### Get Effective Model from ModelBuilderResult Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves the effective Maven model from the ModelBuilderResult after a successful model build. ```java Model model = modelBuilderResult.getModel(); ``` -------------------------------- ### Run specific benchmarks Source: https://github.com/apache/maven/blob/master/impl/maven-xml/BENCHMARKS.md Commands to isolate testing for constructor performance, memory allocation, and thread safety. ```bash mvn test-compile exec:java -Dexec.mainClass="org.openjdk.jmh.Main" \ -Dexec.classpathScope=test \ -Dexec.args="XmlPlexusConfigurationBenchmark.constructor.*" \ -pl impl/maven-xml ``` ```bash mvn test-compile exec:java -Dexec.mainClass="org.openjdk.jmh.Main" \ -Dexec.classpathScope=test \ -Dexec.args="XmlPlexusConfigurationMemoryBenchmark" \ -pl impl/maven-xml ``` ```bash mvn test-compile exec:java -Dexec.mainClass="org.openjdk.jmh.Main" \ -Dexec.classpathScope=test \ -Dexec.args="XmlPlexusConfigurationConcurrencyBenchmark" \ -pl impl/maven-xml ``` -------------------------------- ### Event Interface Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Represents an event during Maven execution, providing methods to get the event type and timestamp. ```APIDOC ## Event Interface Represents an event during Maven execution. ### Methods #### getType() ```java @Nonnull EventType getType() ``` Returns the event type. **Returns:** `EventType` - The type of event --- #### getTimestamp() ```java long getTimestamp() ``` Returns the timestamp when the event occurred. **Returns:** `long` - Milliseconds since epoch ``` -------------------------------- ### Configure Multiple Maven Cache Selectors Source: https://github.com/apache/maven/blob/master/src/site/markdown/cache-configuration.md Apply multiple cache configurations for different request types. This example sets session scope and soft references for ArtifactResolutionRequest, request scope and soft references for ModelBuildRequest, and hard references for ModelBuilderRequest and VersionRangeRequest, with a general fallback for any ModelBuilderRequest. ```bash mvn clean install -Dmaven.cache.config=" ArtifactResolutionRequest { scope: session, ref: soft } ModelBuildRequest { scope: request, ref: soft } ModelBuilderRequest VersionRangeRequest { ref: hard } ModelBuilderRequest * { ref: hard } " ``` -------------------------------- ### Get Source Root Path Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Retrieves the file system path for a project's source root. ```java Path getPath() ``` -------------------------------- ### Mojo Configuration Parameters Source: https://github.com/apache/maven/blob/master/impl/maven-core/lifecycle-executor.txt List of available parameters for configuring Maven Mojo goals. ```APIDOC ## Mojo Configuration Parameters ### Description Defines the configuration parameters available for a Maven Mojo, used to validate POM settings and apply default values during plugin execution. ### Parameters - **appendedResourcesDirectory** (java.io.File) - Optional - Directory for appended resources. - **attached** (boolean) - Optional - Whether the artifact is attached. - **excludeArtifactIds** (java.lang.String) - Optional - Artifact IDs to exclude. - **excludeGroupIds** (java.lang.String) - Optional - Group IDs to exclude. - **excludeScope** (java.lang.String) - Optional - Scope to exclude. - **excludeTransitive** (boolean) - Optional - Whether to exclude transitive dependencies. - **includeArtifactIds** (java.lang.String) - Optional - Artifact IDs to include. - **includeGroupIds** (java.lang.String) - Optional - Group IDs to include. - **includeScope** (java.lang.String) - Optional - Scope to include. - **localRepository** (org.apache.maven.artifact.repository.ArtifactRepository) - Required - The local repository. - **mavenSession** (org.apache.maven.execution.MavenSession) - Required - The Maven session. - **outputDirectory** (java.io.File) - Optional - Output directory path. - **project** (org.apache.maven.project.MavenProject) - Required - The current Maven project. - **properties** (java.util.Map) - Optional - Configuration properties. - **remoteArtifactRepositories** (java.util.List) - Required - List of remote artifact repositories. - **repositories** (java.util.List) - Required - List of repositories. - **resourceBundles** (java.util.List) - Required - List of resource bundles. - **resources** (java.util.List) - Required - List of resources. - **skip** (boolean) - Optional - Whether to skip the execution. - **supplementalModels** (java.lang.String[]) - Optional - Array of supplemental models. ``` -------------------------------- ### Get Parser Request System Properties Source: https://github.com/apache/maven/blob/master/_autodocs/cli-invoker-api.md Retrieves system properties available during the parsing and execution process. ```java @Nonnull Map systemProperties() ``` -------------------------------- ### Session Interface and Core Types Source: https://github.com/apache/maven/blob/master/_autodocs/CONTENTS.txt Documentation for the Session interface and core types like Artifact, Project, and Dependency, including method signatures, parameters, and usage examples. ```APIDOC ## Session Interface and Core Types ### Description This section details the `Session` interface and fundamental types such as `Artifact`, `Project`, and `Dependency`. It provides complete method signatures with parameters, descriptions, and usage examples. ### Key Types Documented - `Session` (40+ methods) - `Artifact` and related types - `Project` interface - `Dependency` and `DependencyCoordinates` - `Node` (dependency graph) - `Version` and `VersionRange` types - `Repository` types (Local, Remote, Workspace) ### Usage Examples Complete working examples for each major method are provided. ``` -------------------------------- ### Get ParserRequest from InvokerRequest Source: https://github.com/apache/maven/blob/master/_autodocs/cli-invoker-api.md Retrieve the ParserRequest associated with this invocation. Useful for inspecting the original parsed arguments. ```java ParserRequest source = invokerRequest.parserRequest(); ``` -------------------------------- ### Access Downloaded Dependency Path Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Shows how to retrieve the file system path of a downloaded dependency. ```java List deps = session.collectDependencies(artifact, scope); for (Node node : deps) { if (node.getArtifact() instanceof DownloadedDependency) { DownloadedDependency dd = (DownloadedDependency) node.getArtifact(); Path path = dd.getPath(); } } ``` -------------------------------- ### Parse and Print Version String Source: https://github.com/apache/maven/blob/master/_autodocs/types-and-enums.md Demonstrates parsing a version string into a Version object and printing its string representation. Requires a Maven Session object. ```java Version v = session.parseVersion("1.0.0"); System.out.println(v); // Prints "1.0.0" ``` -------------------------------- ### withLocalRepository(LocalRepository) Source: https://github.com/apache/maven/blob/master/_autodocs/session-and-core-types.md Creates a derived session using a new local repository. The provided local repository cannot be null. ```APIDOC ## withLocalRepository(LocalRepository) ### Description Creates a derived session using the given local repository. The new local repository must not be null. ### Method Session ### Parameters #### Path Parameters * **localRepository** (LocalRepository) - Required - The new local repository ### Returns * **Session** - The derived session ### Throws * **NullPointerException** - If localRepository is null ### Example ```java LocalRepository newLocal = session.createLocalRepository(Paths.get("/new/repo")); Session derivedSession = session.withLocalRepository(newLocal); ``` ``` -------------------------------- ### Get Resolved Version Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves the concrete version resolved by a VersionResolverResult. Use this to access the final version string. ```java VersionResolverResult result = versionResolver.resolve(request); Version resolved = result.getVersion(); System.out.println("Resolved to: " + resolved); ``` -------------------------------- ### Get Resolved Artifacts Source: https://github.com/apache/maven/blob/master/_autodocs/request-result-types.md Retrieves a collection of downloaded artifacts, each with its file path. Useful for iterating through resolved dependencies. ```java Collection getArtifacts() ``` ```java ArtifactResolverResult result = resolver.resolve(request); for (DownloadedArtifact artifact : result.getArtifacts()) { System.out.println("Resolved: " + artifact + " at " + artifact.getPath()); } ```