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

Maven Polyglot

$
0
0

1. Overview

Maven Polyglot is a set of Maven core extensions that allows the POM model to be written in any language. This includes many scripts and markup languages other than XML.

The primary goal of Maven polyglot is to escape from XML as it’s no longer the go-to language nowadays.

In this tutorial, we’ll first start by understanding the Maven core extension concept and the Maven Polyglot project.

Then, we’ll show how to write a Maven core extension that allows the POM model to be constructed from a JSON file rather than the famous pom.xml.

2. Maven Core Extension Loading Mechanism

The Maven core extensions are plugins loaded at Maven initialization and before the Maven project build start. These plugins allow changing Maven behavior without changing the core.

For example, a plugin loaded at startup can override the Maven default behavior and can read the POM model from another file than the pom.xml.

Technically, a Maven core extension is a Maven artifact declared in an extensions.xml file:

${projectDirectory}/.mvn/extensions.xml

Here’s an example of an extension:

<?xml version="1.0" encoding="UTF-8"?>
<extensions>
    <extension>
        <groupId>com.baeldung.maven.polyglot</groupId>
        <artifactId>maven-polyglot-json-extension</artifactId>
        <version>1.0-SNAPSHOT</version>
    </extension>
</extensions>

Finally, we need to note that this mechanism requires Maven 3.3.1 or higher.

3. Maven Polyglot

Maven Polyglot is a collection of core extensions. Each one of these is responsible for reading the POM model from a script or markup language.

Maven Polyglot provide extensions for the following languages:

+-----------+-------------------+--------------------------------------+
| Language  | Artifact Id       | Accepted POM files                   |
+-----------+-------------------+--------------------------------------+
| Atom      | polyglot-atom     | pom.atom                             |
| Clojure   | polyglot-clojure  | pom.clj                              |
| Groovy    | polyglot-groovy   | pom.groovy, pom.gy                   |
| Java      | polyglot-java     | pom.java                             |
| Kotlin    | polyglot-kotlin   | pom.kts                              |
| Ruby      | polyglot-ruby     | pom.rb, Mavenfile, Jarfile, Gemfile  |
| Scala     | polyglot-scala    | pom.scala                            |
| XML       | polyglot-xml      | pom.xml                            |
| YAML      | polyglot-yaml     | pom.yaml, pom.yml                    |
+-----------+-------------------+--------------------------------------+

In the next sections, we’ll first have a look at building a Maven project using one of the supported languages above.

Then, we’ll write our extension to support a JSON-based POM.

4. Using a Maven Polyglot Extension

One option to build a Maven project based on a different language than XML is to use one of the artifacts provided by the Polyglot project.

In our example, we’ll create a Maven project with a pom.yaml configuration file.

The first step is to create the Maven core extension file:

${projectDirectory}/.mvn/extensions.xml

Then we’ll add the following content:

<?xml version="1.0" encoding="UTF-8"?>
<extensions>
    <extension>
        <groupId>io.takari.polyglot</groupId>
        <artifactId>polyglot-yaml</artifactId>
        <version>0.3.1</version>
    </extension>
</extensions>

Feel free to adjust the artifactId to your chosen language accordingly to the languages above and to check if any new version is available.

The last step is to provide the project metadata in the YAML file:

modelVersion: 4.0.0
groupId: com.baeldung.maven.polyglot
artifactId: maven-polyglot-yml-app
version: 1.0-SNAPSHOT
name: 'YAML Demo'

properties: {maven.compiler.source: 1.8, maven.compiler.target: 1.8}

Now we can run our build as we usually do. For example, we can invoke the command:

mvn clean install

5. Using the Polyglot Translate Plugin

Another option to obtain a project based on one of the supported languages is to use the polyglot-translate-plugin.

This means we can start from an existing Maven project with a traditional pom.xml.

Then, we can convert the existing pom.xml project to the desired polyglot by using the translate plugin:

mvn io.takari.polyglot:polyglot-translate-plugin:translate -Dinput=pom.xml -Doutput=pom.yml

6. Writing a Custom Extension

As JSON is not one of the languages provided by the Maven Polyglot project, we’ll implement a simple extension that allows reading project metadata from a JSON file.

Our extension will provide a custom implementation of the Maven ModelProcessor API which will override the Maven default implementation.

To achieve this, we’ll to change the behavior of how to locate the POM file and how to read and transform the metadata to the Maven Model API.

6.1. Maven Dependencies

We’ll start by creating a Maven project with the following dependencies:

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-core</artifactId>
    <version>3.5.4</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.6</version>
</dependency>

Here we use the maven-core dependency as we’ll implement a core extension. The Jackson dependency is used to deserialize the JSON file.

And as Maven uses the Plexus Dependency Injection container, we need our implementation to be a Plexus component. So we need this plugin to generate the Plexus metadata:

<plugin>
    <groupId>org.codehaus.plexus</groupId>
    <artifactId>plexus-component-metadata</artifactId>
    <version>1.7.1</version>
    <executions>
        <execution>
            <goals>
                <goal>generate-metadata</goal>
            </goals>
        </execution>
    </executions>
</plugin>

6.2. The Custom ModelProcessor Implementation

Maven constructs the POM model by invoking the ModelBuilder.build() method which in turn delegates to the ModelProcessor.read() method.

Maven provides a DefaultModelProcessor implementation which by default reads the POM model from a pom.xml file located at the root directory or specified as a parameter command.

In consequence, we’ll provide a custom ModelProcessor implementation which will override the default behavior. That is the location of the POM model file location and how to read it.

So let’s start by creating a CustomModelProcessor implementation and mark it as a Plexus component:

@Component(role = ModelProcessor.class)
public class CustomModelProcessor implements ModelProcessor {

    @Override
    public File locatePom(File projectDirectory) {
        return null;
    }

    @Override
    public Model read(
      InputStream input, 
      Map<String, ?> options) throws IOException, ModelParseException {
        return null;
    }
    //...
}

The @Component annotation will make the implementation available for injection by the DI container (Plexus). So, when Maven needs a ModelProcessor injection in the ModelBuilder, the Plexus container will provide this implementation and not the DefaultModelProcessor.

Next, we’ll provide the implementation for the locatePom() method. This method returns the file where Maven will read the project metadata.

So we’ll return a pom.json file if it exists, otherwise, the pom.xml as we usually do:

@Override
public File locatePom(File projectDirectory) {
    File pomFile = new File(projectDirectory, "pom.json");
    if (!pomFile.exists()) {
        pomFile = new File(projectDirectory, "pom.xml");
    }
    return pomFile;
}

The next step is to read this file and transform it to the Maven Model. This is achieved by the read() method:

@Requirement
private ModelReader modelReader;

@Override
public Model read(InputStream input, Map<String, ?> options) 
  throws IOException, ModelParseException {
 
    FileModelSource source = getFileFromOptions(options);
    try (InputStream is = input) {
        //JSON FILE ==> Jackson
        if (isJsonFile(source)) {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(input, Model.class);
        } else {
            // XML FILE ==> DefaultModelReader
            return modelReader.read(input, options);
        }
    }
    return model;
}

In this example, we check if the file is a JSON file and we use the Jackson to deserialize it to a Maven Model. Otherwise, it’s a normal XML file, and it will be read by the Maven DefaultModelReader.

We need to build the extension, and it will be ready for use:

mvn clean install

6.3. Using the Extension

To demonstrate the use of the extension, we’ll use a Spring Boot Web project.

First, we’ll create a Maven project, and delete the pom.xml.

Then, we’ll add the extension that we have implemented above, in ${projectDirectory}/.mvn/extensions.xml:

<?xml version="1.0" encoding="UTF-8"?>
<extensions>
    <extension>
        <groupId>com.baeldung.maven.polyglot</groupId>
        <artifactId>maven-polyglot-json-extension</artifactId>
        <version>1.0-SNAPSHOT</version>
    </extension>
</extensions>

And finally we create the pom.json with the following content:

{
  "modelVersion": "4.0.0",
  "groupId": "com.baeldung.maven.polyglot",
  "artifactId": "maven-polyglot-json-app",
  "version": "1.0.1",
  "name": "Json Maven Polyglot",
  "parent": {
    "groupId": "org.springframework.boot",
    "artifactId": "spring-boot-starter-parent",
    "version": "2.0.5.RELEASE",
    "relativePath": null
  },
  "properties": {
    "project.build.sourceEncoding": "UTF-8",
    "project.reporting.outputEncoding": "UTF-8",
    "maven.compiler.source": "1.8",
    "maven.compiler.target": "1.8",
    "java.version": "1.8"
  },
  "dependencies": [
    {
      "groupId": "org.springframework.boot",
      "artifactId": "spring-boot-starter-web"
    }
  ],
  "build": {
    "plugins": [
      {
        "groupId": "org.springframework.boot",
        "artifactId": "spring-boot-maven-plugin"
      }
    ]
  }
}

We can now run the project with the command:

mvn spring-boot:run

7. Conclusion

In this article, we’ve demonstrated how we can change the default Maven behavior through the Maven Polyglot project. To achieve this goal we have used the new Maven 3.3.1 feature that simplifies the core components loading.

The code and all the samples can be found as usual over on Github.


Viewing all articles
Browse latest Browse all 4535

Trending Articles