Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

Run Maven From Java Code

$
0
0

1. Overview

Maven is an integral tool for the majority of Java projects. It provides a convenient way to run and configure the build. However, in some cases, we need more control over the process. Running a Maven build from Java makes it more configurable, as we can make many decisions at runtime.

In this tutorial, we’ll learn how to interact with Maven and run builds directly from the code.

2. Learning Platform

Let’s consider the following example to better understand the goal and usefulness of working with Maven directly from Java: Imagine a Java learning platform where students can choose from various topics and work on assignments.

Because our platform mainly targets beginners, we want to streamline the entire experience as much as possible. Thus, students can choose any topic they want or even combine them. We generate the project on the server, and students complete it online.

To generate a project from scratch, we’ll be using a maven-model library from Apache:

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-model</artifactId>
    <version>3.9.6</version>
</dependency>

Our builder will take simple steps to create a POM file with the initial information:

public class ProjectBuilder {
    // constants
    public ProjectBuilder addDependency(String groupId, String artifactId, String version) {
        Dependency dependency = new Dependency();
        dependency.setGroupId(groupId);
        dependency.setArtifactId(artifactId);
        dependency.setVersion(version);
        dependencies.add(dependency);
        return this;
    }
    public ProjectBuilder setJavaVersion(JavaVersion version) {
        this.javaVersion = version;
        return this;
    }
    public void build(String userName, Path projectPath, String packageName) throws IOException {
        Model model = new Model();
        configureModel(userName, model);
        dependencies.forEach(model::addDependency);
        Build build = configureJavaVersion();
        model.setBuild(build);
        MavenXpp3Writer writer = new MavenXpp3Writer();
        writer.write(new FileWriter(projectPath.resolve(POM_XML).toFile()), model);
        generateFolders(projectPath, SRC_TEST);
        Path generatedPackage = generateFolders(projectPath,
          SRC_MAIN_JAVA +
            packageName.replace(PACKAGE_DELIMITER, FileSystems.getDefault().getSeparator()));
        String generatedClass = generateMainClass(PACKAGE + packageName);
        Files.writeString(generatedPackage.resolve(MAIN_JAVA), generatedClass);
   }
   // utility methods
}

First, we ensure that all students have the correct environment. Second, we reduce the steps they need to take, from getting an assignment to starting coding. Setting up an environment might be trivial, but dealing with dependency management and configuration before writing their first “Hello World” program might be too much for beginners.

Also, we want to introduce a wrapper that would interact with Maven from Java:

public interface Maven {
    String POM_XML = "pom.xml";
    String COMPILE_GOAL = "compile";
    String USE_CUSTOM_POM = "-f";
    int OK = 0;
    String MVN = "mvn";
    void compile(Path projectFolder);
}

For now, this wrapper would only compile the project. However, we can extend it with additional operations.

3. Universal Executors

Firstly, let’s check the tool where we can run simple scripts. Thus, the solution isn’t specific to Maven, but we can run mvn commands. We have two options: Runtime.exec and ProcessBuilderThey are so similar that we can use an additional abstract class to handle exceptions:

public abstract class MavenExecutorAdapter implements Maven {
    @Override
    public void compile(Path projectFolder) {
        int exitCode;
        try {
            exitCode = execute(projectFolder, COMPILE_GOAL);
        } catch (InterruptedException e) {
            throw new MavenCompilationException("Interrupted during compilation", e);
        } catch (IOException e) {
            throw new MavenCompilationException("Incorrect execution", e);
        }
        if (exitCode != OK) {
            throw new MavenCompilationException("Failure during compilation: " + exitCode);
        }
    }
    protected abstract int execute(Path projectFolder, String compileGoal)
      throws InterruptedException, IOException;
}

3.1. Runtime Executor

Let’s check how we can run a simple command with Runtime.exec(String[]):

public class MavenRuntimeExec extends MavenExecutorAdapter {
    @Override
    protected int execute(Path projectFolder, String compileGoal) throws InterruptedException, IOException {
        String[] arguments = {MVN, USE_CUSTOM_POM, projectFolder.resolve(POM_XML).toString(), COMPILE_GOAL};
        Process process = Runtime.getRuntime().exec(arguments);
        return process.waitFor();
    }
}

This is quite a straightforward approach for any scripts and commands we need to run from Java.

3.2. Process Builder

Another option is ProcessBuilder. It’s similar to the previous solution but provides a slightly better API:

public class MavenProcessBuilder extends MavenExecutorAdapter {
    private static final ProcessBuilder PROCESS_BUILDER = new ProcessBuilder();
    protected int execute(Path projectFolder, String compileGoal) throws IOException, InterruptedException {
        Process process = PROCESS_BUILDER
          .command(MVN, USE_CUSTOM_POM, projectFolder.resolve(POM_XML).toString(), compileGoal)
          .start();
        return process.waitFor();
    }
}

From Java 9, ProcessBuilder can use pipelines that look similar to Streams. This way, we can run the build and trigger additional processing.

4. Maven APIs

Now, let’s consider the solution that is tailored for Maven. There are two options: MavenEmbedder and MavenInvoker.

4.1. MavenEmbedder

While previous solutions didn’t require any additional dependencies, for this one, we need to use the following package:

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-embedder</artifactId>
    <version>3.9.6</version>
</dependency>

This library provides us with a high-level API and simplifies the interaction with Maven:

public class MavenEmbedder implements Maven {
    public static final String MVN_HOME = "maven.multiModuleProjectDirectory";
    @Override
    public void compile(Path projectFolder) {
        MavenCli cli = new MavenCli();
        System.setProperty(MVN_HOME, projectFolder.toString());
        cli.doMain(new String[]{COMPILE_GOAL}, projectFolder.toString(), null, null);
    }
}

4.2. MavenInvoker

Another tool similar to MavenEmbedder is MavenInvoker. To use it, we also need to import a library:

<dependency>
    <groupId>org.apache.maven.shared</groupId>
    <artifactId>maven-invoker</artifactId>
    <version>3.2.0</version>
</dependency>

It also provides a nice high-level API for interaction:

public class MavenInvoker implements Maven {
    @Override
    public void compile(Path projectFolder) {
        InvocationRequest request = new DefaultInvocationRequest();
        request.setPomFile(projectFolder.resolve(POM_XML).toFile());
        request.setGoals(Collections.singletonList(Maven.COMPILE_GOAL));
        Invoker invoker = new DefaultInvoker();
        try {
            InvocationResult result = invoker.execute(request);
            if (result.getExitCode() != 0) {
                throw new MavenCompilationException("Build failed", result.getExecutionException());
            }
        } catch (MavenInvocationException e) {
            throw new MavenCompilationException("Exception during Maven invocation", e);
        }
    }
}

5. Testing

Now, we can ensure that we create and compile a project:

class MavenRuntimeExecUnitTest {
    private static final String PACKAGE_NAME = "com.baeldung.generatedcode";
    private static final String USER_NAME = "john_doe";
    @TempDir
    private Path tempDir;
    @BeforeEach
    public void setUp() throws IOException {
        ProjectBuilder projectBuilder = new ProjectBuilder();
        projectBuilder.build(USER_NAME, tempDir, PACKAGE_NAME);
    }
    @ParameterizedTest
    @MethodSource
    void givenMavenInterface_whenCompileMavenProject_thenCreateTargetDirectory(Maven maven) {
        maven.compile(tempDir);
        assertTrue(Files.exists(tempDir));
    }
    static Stream<Maven> givenMavenInterface_whenCompileMavenProject_thenCreateTargetDirectory() {
        return Stream.of(
          new MavenRuntimeExec(),
          new MavenProcessBuilder(),
          new MavenEmbedder(),
          new MavenInvoker());
    }
}

We generated an object from scratch and compiled it directly from Java code. Although we don’t encounter such requirements daily, automating Maven processes may benefit some projects.

6. Conclusion

Maven configure and build a project based on a POM file. However, the XML configuration doesn’t work well with dynamic parameters and conditional logic.

We can leverage Java code to set up a Maven build by running it directly from the code. The best way to achieve this is to use specific libraries, like MavenEmbedder or MavenInvoker. At the same time, there are several, more low-level methods to get a similar result.

As usual, all the code from this tutorial is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>