You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by sl...@apache.org on 2026/10/18 17:34:32 UTC

(maven-dependency-plugin) 01/02: [MDEP-522] Add the json and pom output types to dependency:list and resolve

This is an automated email from the ASF dual-hosted git repository.

slachiewicz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-dependency-plugin.git

commit ff2456117bbb1294d96a805b028c9b583724d0f5
Author: Sylwester Lachiewicz <sl...@apache.org>
AuthorDate: Tue Oct 13 23:52:49 2026 +0200

    [MDEP-522] Add the json and pom output types to dependency:list and resolve
---
 .../projects/list-output-type/invoker.properties   |  25 +++
 src/it/projects/list-output-type/json.properties   |  19 ++
 src/it/projects/list-output-type/pom.properties    |  20 ++
 src/it/projects/list-output-type/pom.xml           |  55 ++++++
 src/it/projects/list-output-type/text.properties   |  19 ++
 src/it/projects/list-output-type/verify.groovy     |  64 +++++++
 .../resolvers/ResolveDependenciesMojo.java         |  40 +++-
 .../resolvers/ResolvedDependenciesFormat.java      | 182 ++++++++++++++++++
 src/site/markdown/usage.md.vm                      |  10 +
 .../resolvers/ResolvedDependenciesFormatTest.java  | 209 +++++++++++++++++++++
 10 files changed, 642 insertions(+), 1 deletion(-)

diff --git a/src/it/projects/list-output-type/invoker.properties b/src/it/projects/list-output-type/invoker.properties
new file mode 100644
index 00000000..ea5e9c17
--- /dev/null
+++ b/src/it/projects/list-output-type/invoker.properties
@@ -0,0 +1,25 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+# 
+#   http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+invoker.goals.1 = ${project.groupId}:${project.artifactId}:${project.version}:list
+invoker.userPropertiesFile.1 = json.properties
+
+invoker.goals.2 = ${project.groupId}:${project.artifactId}:${project.version}:list
+invoker.userPropertiesFile.2 = pom.properties
+
+invoker.goals.3 = ${project.groupId}:${project.artifactId}:${project.version}:list
+invoker.userPropertiesFile.3 = text.properties
diff --git a/src/it/projects/list-output-type/json.properties b/src/it/projects/list-output-type/json.properties
new file mode 100644
index 00000000..df2df1b9
--- /dev/null
+++ b/src/it/projects/list-output-type/json.properties
@@ -0,0 +1,19 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+# 
+#   http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+outputType = json
+outputFile = target/list.json
diff --git a/src/it/projects/list-output-type/pom.properties b/src/it/projects/list-output-type/pom.properties
new file mode 100644
index 00000000..3151e213
--- /dev/null
+++ b/src/it/projects/list-output-type/pom.properties
@@ -0,0 +1,20 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+# 
+#   http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+outputType = pom
+outputFile = target/list.pom.xml
+sort = true
diff --git a/src/it/projects/list-output-type/pom.xml b/src/it/projects/list-output-type/pom.xml
new file mode 100644
index 00000000..c8a8e0dc
--- /dev/null
+++ b/src/it/projects/list-output-type/pom.xml
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements.  See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership.  The ASF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License.  You may obtain a copy of the License at
+  ~
+  ~   http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied.  See the License for the
+  ~ specific language governing permissions and limitations
+  ~ under the License.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.plugins.dependency.its</groupId>
+  <artifactId>list-output-type</artifactId>
+  <version>1.0-SNAPSHOT</version>
+
+  <description>
+    dependency:list with outputType json and pom.
+  </description>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.maven.its.dependency</groupId>
+      <artifactId>ResourceArtifact</artifactId>
+      <version>1.0</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.maven.its.dependency</groupId>
+      <artifactId>ResourceArtifact</artifactId>
+      <version>1.0</version>
+      <classifier>client</classifier>
+      <scope>runtime</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.maven.its.dependency</groupId>
+      <artifactId>ResourceArtifact</artifactId>
+      <version>1.0</version>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+</project>
diff --git a/src/it/projects/list-output-type/text.properties b/src/it/projects/list-output-type/text.properties
new file mode 100644
index 00000000..3c901fda
--- /dev/null
+++ b/src/it/projects/list-output-type/text.properties
@@ -0,0 +1,19 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+# 
+#   http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+outputFile = target/list.txt
+includeModuleInfo = false
diff --git a/src/it/projects/list-output-type/verify.groovy b/src/it/projects/list-output-type/verify.groovy
new file mode 100644
index 00000000..9b72b23e
--- /dev/null
+++ b/src/it/projects/list-output-type/verify.groovy
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import groovy.json.JsonSlurper
+
+import static org.assertj.core.api.Assertions.assertThat
+
+def json = new JsonSlurper().parse(new File(basedir, "target/list.json"))
+assertThat(json.keySet()).containsExactly("resolved", "skipped", "unresolved")
+assertThat(json.resolved).hasSize(3)
+assertThat(json.skipped).isEmpty()
+assertThat(json.unresolved).isEmpty()
+def byScope = json.resolved.collectEntries { [it.scope, it] }
+assertThat(byScope.compile).containsEntry("artifactId", "ResourceArtifact").containsEntry("type", "jar").containsEntry("classifier", "")
+assertThat(byScope.runtime).containsEntry("classifier", "client")
+assertThat(byScope.test).containsEntry("type", "test-jar").containsEntry("classifier", "tests")
+
+def pom = new File(basedir, "target/list.pom.xml").text.replace("\r\n", "\n")
+assertThat(pom).isEqualTo("""<dependencies>
+  <dependency>
+    <groupId>org.apache.maven.its.dependency</groupId>
+    <artifactId>ResourceArtifact</artifactId>
+    <version>1.0</version>
+  </dependency>
+  <dependency>
+    <groupId>org.apache.maven.its.dependency</groupId>
+    <artifactId>ResourceArtifact</artifactId>
+    <version>1.0</version>
+    <classifier>client</classifier>
+    <scope>runtime</scope>
+  </dependency>
+  <dependency>
+    <groupId>org.apache.maven.its.dependency</groupId>
+    <artifactId>ResourceArtifact</artifactId>
+    <version>1.0</version>
+    <type>test-jar</type>
+    <classifier>tests</classifier>
+    <scope>test</scope>
+  </dependency>
+</dependencies>
+""")
+
+// the default output is unchanged
+def text = new File(basedir, "target/list.txt").text
+assertThat(text).startsWith("The following files have been resolved:")
+assertThat(text).contains("org.apache.maven.its.dependency:ResourceArtifact:jar:1.0:compile")
+
+return true
diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojo.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojo.java
index 498c460f..2fddcba2 100644
--- a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojo.java
+++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolveDependenciesMojo.java
@@ -93,6 +93,27 @@ public class ResolveDependenciesMojo extends AbstractResolveMojo {
     @Parameter(property = "outputAbsoluteArtifactFilename", defaultValue = "false")
     private boolean outputAbsoluteArtifactFilename;
 
+    /**
+     * The format of the output: <code>text</code> (default), <code>json</code> or <code>pom</code>.
+     * <p>
+     * <code>json</code> writes an object with the arrays <code>resolved</code>, <code>skipped</code> and
+     * <code>unresolved</code>, whose elements have the string members <code>groupId</code>,
+     * <code>artifactId</code>, <code>version</code>, <code>type</code>, <code>scope</code>, <code>classifier</code>
+     * and <code>optional</code>, like the JSON of <code>dependency:tree</code>, and <code>file</code> with
+     * <code>outputAbsoluteArtifactFilename</code>.
+     * </p>
+     * <p>
+     * <code>pom</code> writes the resolved artifacts as a <code>&lt;dependencies&gt;</code> fragment, with
+     * <code>type</code> unless it is <code>jar</code>, <code>classifier</code> if there is one and
+     * <code>scope</code> unless it is <code>compile</code>, to paste into <code>dependencyManagement</code>.
+     * </p>
+     * Both ignore <code>outputScope</code> and <code>includeModuleInfo</code>.
+     *
+     * @since 3.12.0
+     */
+    @Parameter(property = "outputType", defaultValue = "text")
+    String outputType;
+
     /**
      * Only used to store results for integration test validation.
      */
@@ -142,10 +163,15 @@ public class ResolveDependenciesMojo extends AbstractResolveMojo {
      */
     @Override
     protected void doExecute() throws MojoExecutionException {
+        if (!ResolvedDependenciesFormat.isSupported(outputType)) {
+            throw new MojoExecutionException(
+                    "Unsupported outputType '" + outputType + "', use one of text, json or pom");
+        }
+
         // get sets of dependencies
         results = this.getDependencySets(false, includeParents);
 
-        String output = getOutput(outputAbsoluteArtifactFilename, outputScope, sort);
+        String output = formatOutput();
         try {
             if (outputFile == null) {
                 DependencyUtil.log(output, getLog());
@@ -158,6 +184,18 @@ public class ResolveDependenciesMojo extends AbstractResolveMojo {
         }
     }
 
+    /**
+     * @return the results in the format of {@link #outputType}
+     */
+    String formatOutput() {
+        if (ResolvedDependenciesFormat.JSON.equals(outputType)) {
+            return ResolvedDependenciesFormat.json(results, outputAbsoluteArtifactFilename, sort);
+        } else if (ResolvedDependenciesFormat.POM.equals(outputType)) {
+            return ResolvedDependenciesFormat.pom(results, sort);
+        }
+        return getOutput(outputAbsoluteArtifactFilename, outputScope, sort);
+    }
+
     /**
      * @return returns the results
      */
diff --git a/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolvedDependenciesFormat.java b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolvedDependenciesFormat.java
new file mode 100644
index 00000000..f07fce73
--- /dev/null
+++ b/src/main/java/org/apache/maven/plugins/dependency/resolvers/ResolvedDependenciesFormat.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.plugins.dependency.resolvers;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Objects;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.plugins.dependency.utils.DependencyStatusSets;
+
+/**
+ * The machine-readable output types of {@link ResolveDependenciesMojo}: a JSON document with the resolved, skipped and
+ * unresolved artifacts, and a POM <code>dependencies</code> fragment of the resolved artifacts.
+ */
+final class ResolvedDependenciesFormat {
+
+    static final String TEXT = "text";
+
+    static final String JSON = "json";
+
+    static final String POM = "pom";
+
+    private static final Comparator<Artifact> BY_COORDINATES = Comparator.comparing(Artifact::getGroupId)
+            .thenComparing(Artifact::getArtifactId)
+            .thenComparing(Artifact::getVersion)
+            .thenComparing(Artifact::getType)
+            .thenComparing(a -> Objects.toString(a.getClassifier(), ""));
+
+    private ResolvedDependenciesFormat() {}
+
+    static boolean isSupported(String outputType) {
+        return outputType == null || TEXT.equals(outputType) || JSON.equals(outputType) || POM.equals(outputType);
+    }
+
+    /**
+     * Writes the sets as <code>{"resolved": [...], "skipped": [...], "unresolved": [...]}</code>. The members of an
+     * artifact follow the JSON of <code>dependency:tree</code>: <code>groupId</code>, <code>artifactId</code>,
+     * <code>version</code>, <code>type</code>, <code>scope</code>, <code>classifier</code> (empty if none) and
+     * <code>optional</code>, all strings. <code>file</code> is added if requested and the artifact has one.
+     */
+    static String json(DependencyStatusSets sets, boolean withFile, boolean sort) {
+        String nl = System.lineSeparator();
+        StringBuilder sb = new StringBuilder("{").append(nl);
+        jsonArray(sb, "resolved", sets.getResolvedDependencies(), withFile, sort)
+                .append(",")
+                .append(nl);
+        jsonArray(sb, "skipped", sets.getSkippedDependencies(), withFile, sort)
+                .append(",")
+                .append(nl);
+        jsonArray(sb, "unresolved", sets.getUnResolvedDependencies(), withFile, sort)
+                .append(nl);
+        return sb.append("}").append(nl).toString();
+    }
+
+    private static StringBuilder jsonArray(
+            StringBuilder sb, String name, Collection<Artifact> artifacts, boolean withFile, boolean sort) {
+        String nl = System.lineSeparator();
+        List<Artifact> list = ordered(artifacts, sort);
+        sb.append("  \"").append(name).append("\": [");
+        if (list.isEmpty()) {
+            return sb.append("]");
+        }
+        sb.append(nl);
+        for (int i = 0; i < list.size(); i++) {
+            Artifact artifact = list.get(i);
+            List<String[]> members = new ArrayList<>();
+            members.add(new String[] {"groupId", artifact.getGroupId()});
+            members.add(new String[] {"artifactId", artifact.getArtifactId()});
+            members.add(new String[] {"version", artifact.getVersion()});
+            members.add(new String[] {"type", artifact.getType()});
+            members.add(new String[] {"scope", artifact.getScope()});
+            members.add(new String[] {"classifier", artifact.getClassifier()});
+            members.add(new String[] {"optional", String.valueOf(artifact.isOptional())});
+            if (withFile && artifact.getFile() != null) {
+                members.add(new String[] {"file", artifact.getFile().getAbsolutePath()});
+            }
+            sb.append("    {").append(nl);
+            for (int j = 0; j < members.size(); j++) {
+                sb.append("      \"")
+                        .append(members.get(j)[0])
+                        .append("\": \"")
+                        .append(jsonEscape(members.get(j)[1]))
+                        .append("\"")
+                        .append(j < members.size() - 1 ? "," : "")
+                        .append(nl);
+            }
+            sb.append("    }").append(i < list.size() - 1 ? "," : "").append(nl);
+        }
+        return sb.append("  ]");
+    }
+
+    /**
+     * Writes the resolved artifacts as a <code>dependencies</code> element that can be pasted into
+     * <code>dependencyManagement</code> or <code>dependencies</code>. <code>type</code> is left out for
+     * <code>jar</code>, <code>classifier</code> if there is none, and <code>scope</code> for
+     * <code>compile</code>. The version is the base version, as written in a POM.
+     */
+    static String pom(DependencyStatusSets sets, boolean sort) {
+        String nl = System.lineSeparator();
+        StringBuilder sb = new StringBuilder("<dependencies>").append(nl);
+        for (Artifact artifact : ordered(sets.getResolvedDependencies(), sort)) {
+            sb.append("  <dependency>").append(nl);
+            element(sb, "groupId", artifact.getGroupId());
+            element(sb, "artifactId", artifact.getArtifactId());
+            element(sb, "version", artifact.getBaseVersion());
+            if (!"jar".equals(artifact.getType())) {
+                element(sb, "type", artifact.getType());
+            }
+            if (artifact.hasClassifier()) {
+                element(sb, "classifier", artifact.getClassifier());
+            }
+            if (artifact.getScope() != null && !Artifact.SCOPE_COMPILE.equals(artifact.getScope())) {
+                element(sb, "scope", artifact.getScope());
+            }
+            sb.append("  </dependency>").append(nl);
+        }
+        return sb.append("</dependencies>").append(nl).toString();
+    }
+
+    private static void element(StringBuilder sb, String name, String value) {
+        sb.append("    <")
+                .append(name)
+                .append('>')
+                .append(xmlEscape(value))
+                .append("</")
+                .append(name)
+                .append('>')
+                .append(System.lineSeparator());
+    }
+
+    private static List<Artifact> ordered(Collection<Artifact> artifacts, boolean sort) {
+        if (artifacts == null) {
+            return Collections.emptyList();
+        }
+        List<Artifact> list = new ArrayList<>(artifacts);
+        if (sort) {
+            list.sort(BY_COORDINATES);
+        }
+        return list;
+    }
+
+    private static String jsonEscape(String value) {
+        if (value == null) {
+            return "";
+        }
+        StringBuilder sb = new StringBuilder(value.length());
+        for (char c : value.toCharArray()) {
+            if (c == '"' || c == '\\') {
+                sb.append('\\').append(c);
+            } else if (c < 0x20) {
+                sb.append(String.format("\\u%04x", (int) c));
+            } else {
+                sb.append(c);
+            }
+        }
+        return sb.toString();
+    }
+
+    private static String xmlEscape(String value) {
+        return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
+    }
+}
diff --git a/src/site/markdown/usage.md.vm b/src/site/markdown/usage.md.vm
index 54016503..97d2c4d9 100644
--- a/src/site/markdown/usage.md.vm
+++ b/src/site/markdown/usage.md.vm
@@ -353,6 +353,16 @@ Maven resolves the dependencies before the goal runs, so every dependency must b
 
 Artifacts can also be resolved by specifying the classifier and optionally type. Type is only used with the classifier and defaults to java-sources. When the classifier is set, the list of dependencies is used as the base to resolve artifacts with the classifier and type. For example: `mvn dependency:resolve -Dclassifier=test-jar` will try to find the test-jar for all dependencies resolve them to the local repository.
 
+The `outputType` parameter (since 3.12.0) of `dependency:resolve`, `dependency:list` and `dependency:collect` selects a machine-readable output, which `outputFile` writes to a file:
+
+- `text` is the default listing.
+- `json` writes an object with the arrays `resolved`, `skipped` and `unresolved`. Each element has the string members `groupId`, `artifactId`, `version`, `type`, `scope`, `classifier` and `optional` of the JSON of `dependency:tree`, and `file` with `-DoutputAbsoluteArtifactFilename`.
+- `pom` writes the resolved artifacts as a `<dependencies>` fragment, with `type` unless it is `jar`, `classifier` if there is one and `scope` unless it is `compile`, for example to start a `dependencyManagement` section.
+
+```
+mvn dependency:list -DoutputType=pom -DoutputFile=dependencies.xml
+```
+
 `dependency:resolve-sources`
 ----------------------------
 
diff --git a/src/test/java/org/apache/maven/plugins/dependency/resolvers/ResolvedDependenciesFormatTest.java b/src/test/java/org/apache/maven/plugins/dependency/resolvers/ResolvedDependenciesFormatTest.java
new file mode 100644
index 00000000..175ba39d
--- /dev/null
+++ b/src/test/java/org/apache/maven/plugins/dependency/resolvers/ResolvedDependenciesFormatTest.java
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.plugins.dependency.resolvers;
+
+import java.io.File;
+import java.io.StringReader;
+import java.util.Arrays;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import jakarta.json.Json;
+import jakarta.json.JsonArray;
+import jakarta.json.JsonObject;
+import jakarta.json.JsonReader;
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.artifact.DefaultArtifact;
+import org.apache.maven.artifact.handler.DefaultArtifactHandler;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugins.dependency.utils.DependencyStatusSets;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ResolvedDependenciesFormatTest {
+
+    private static final String NL = System.lineSeparator();
+
+    private static Artifact artifact(
+            String artifactId, String version, String scope, String type, String classifier, boolean optional) {
+        DefaultArtifactHandler handler = new DefaultArtifactHandler(type) {
+            @Override
+            public String getClassifier() {
+                return "test-jar".equals(type) ? "tests" : null;
+            }
+        };
+        DefaultArtifact artifact = new DefaultArtifact("g", artifactId, version, scope, type, classifier, handler);
+        artifact.setOptional(optional);
+        return artifact;
+    }
+
+    private static Set<Artifact> set(Artifact... artifacts) {
+        return new LinkedHashSet<>(Arrays.asList(artifacts));
+    }
+
+    private static JsonObject parse(String json) {
+        System.setProperty("jakarta.json.provider", "org.glassfish.json.JsonProviderImpl");
+        try (JsonReader reader = Json.createReader(new StringReader(json))) {
+            return reader.readObject();
+        }
+    }
+
+    @Test
+    void pomOmitsTypeJarClassifierNoneAndScopeCompile() {
+        DependencyStatusSets sets =
+                new DependencyStatusSets(set(artifact("a", "1.0", "compile", "jar", null, false)), null, null);
+
+        assertEquals(
+                "<dependencies>" + NL
+                        + "  <dependency>" + NL
+                        + "    <groupId>g</groupId>" + NL
+                        + "    <artifactId>a</artifactId>" + NL
+                        + "    <version>1.0</version>" + NL
+                        + "  </dependency>" + NL
+                        + "</dependencies>" + NL,
+                ResolvedDependenciesFormat.pom(sets, false));
+    }
+
+    @Test
+    void pomWritesTypeClassifierAndScopeWhenTheyAreNotTheDefaults() {
+        DependencyStatusSets sets = new DependencyStatusSets(
+                set(
+                        artifact("b", "2.0", "test", "test-jar", "tests", false),
+                        artifact("c", "3.0", "runtime", "jar", "client", false),
+                        artifact("d", "4.0", "provided", "pom", null, false)),
+                null,
+                null);
+
+        String pom = ResolvedDependenciesFormat.pom(sets, false);
+
+        assertTrue(
+                pom.contains("<type>test-jar</type>" + NL + "    <classifier>tests</classifier>" + NL
+                        + "    <scope>test</scope>"),
+                pom);
+        assertTrue(pom.contains("<classifier>client</classifier>" + NL + "    <scope>runtime</scope>"), pom);
+        assertTrue(pom.contains("<type>pom</type>" + NL + "    <scope>provided</scope>"), pom);
+    }
+
+    @Test
+    void pomUsesTheBaseVersionOfSnapshotsAndOnlyListsResolvedArtifacts() {
+        Artifact snapshot = artifact("s", "1.0-20240101.120000-1", "compile", "jar", null, false);
+        snapshot.setBaseVersion("1.0-SNAPSHOT");
+        DependencyStatusSets sets = new DependencyStatusSets(
+                set(snapshot),
+                set(artifact("missing", "1.0", "compile", "jar", null, false)),
+                set(artifact("skipped", "1.0", "compile", "jar", null, false)));
+
+        String pom = ResolvedDependenciesFormat.pom(sets, false);
+
+        assertTrue(pom.contains("<version>1.0-SNAPSHOT</version>"), pom);
+        assertFalse(pom.contains("missing"), pom);
+        assertFalse(pom.contains("skipped"), pom);
+    }
+
+    @Test
+    void pomIsEmptyElementWithoutArtifactsAndSorts() {
+        assertEquals(
+                "<dependencies>" + NL + "</dependencies>" + NL,
+                ResolvedDependenciesFormat.pom(new DependencyStatusSets(), false));
+
+        DependencyStatusSets sets = new DependencyStatusSets(
+                set(
+                        artifact("z", "1.0", "compile", "jar", null, false),
+                        artifact("a", "1.0", "compile", "jar", null, false)),
+                null,
+                null);
+        String pom = ResolvedDependenciesFormat.pom(sets, true);
+        assertTrue(pom.indexOf("<artifactId>a<") < pom.indexOf("<artifactId>z<"), pom);
+        pom = ResolvedDependenciesFormat.pom(sets, false);
+        assertTrue(pom.indexOf("<artifactId>z<") < pom.indexOf("<artifactId>a<"), pom);
+    }
+
+    @Test
+    void jsonHasThreeArraysWithTheTreeMembers() {
+        DependencyStatusSets sets = new DependencyStatusSets(
+                set(artifact("a", "1.0", "test", "jar", "client", true)),
+                set(artifact("missing", "2.0", "compile", "jar", null, false)),
+                null);
+
+        JsonObject json = parse(ResolvedDependenciesFormat.json(sets, false, false));
+
+        JsonArray resolved = json.getJsonArray("resolved");
+        assertEquals(1, resolved.size());
+        JsonObject a = resolved.getJsonObject(0);
+        assertEquals("g", a.getString("groupId"));
+        assertEquals("a", a.getString("artifactId"));
+        assertEquals("1.0", a.getString("version"));
+        assertEquals("jar", a.getString("type"));
+        assertEquals("test", a.getString("scope"));
+        assertEquals("client", a.getString("classifier"));
+        assertEquals("true", a.getString("optional"));
+        assertFalse(a.containsKey("file"));
+        assertEquals(0, json.getJsonArray("skipped").size());
+        assertEquals("missing", json.getJsonArray("unresolved").getJsonObject(0).getString("artifactId"));
+        assertEquals("", json.getJsonArray("unresolved").getJsonObject(0).getString("classifier"));
+    }
+
+    @Test
+    void jsonAddsTheFileAndEscapesIt() {
+        Artifact artifact = artifact("a", "1.0", "compile", "jar", null, false);
+        artifact.setFile(new File("target/with \"quote\".jar"));
+
+        JsonObject json = parse(
+                ResolvedDependenciesFormat.json(new DependencyStatusSets(set(artifact), null, null), true, false));
+
+        assertEquals(
+                artifact.getFile().getAbsolutePath(),
+                json.getJsonArray("resolved").getJsonObject(0).getString("file"));
+    }
+
+    @Test
+    void jsonOfNothingIsThreeEmptyArrays() {
+        JsonObject json = parse(ResolvedDependenciesFormat.json(new DependencyStatusSets(), false, true));
+
+        assertEquals(3, json.size());
+        assertTrue(json.getJsonArray("resolved").isEmpty());
+    }
+
+    @Test
+    void unsupportedOutputTypeFailsTheMojo() {
+        ResolveDependenciesMojo mojo = new ResolveDependenciesMojo(null, null, null, null, null, null);
+        mojo.outputType = "yaml";
+
+        assertThrows(MojoExecutionException.class, mojo::doExecute);
+    }
+
+    @Test
+    void mojoFormatsByOutputType() {
+        ResolveDependenciesMojo mojo = new ResolveDependenciesMojo(null, null, null, null, null, null);
+        mojo.results = new DependencyStatusSets(set(artifact("a", "1.0", "compile", "jar", null, false)), null, null);
+
+        mojo.outputType = "pom";
+        assertTrue(mojo.formatOutput().startsWith("<dependencies>"));
+        mojo.outputType = "json";
+        assertTrue(mojo.formatOutput().startsWith("{"));
+        mojo.outputType = "text";
+        assertTrue(mojo.formatOutput().contains("The following files have been resolved:"));
+        mojo.outputType = null;
+        assertTrue(mojo.formatOutput().contains("The following files have been resolved:"));
+    }
+}