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

gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/master by this push:
     new 052aa7ec5d Add PluginManager API and Realm for scoped plugin service 
discovery (#13625)
052aa7ec5d is described below

commit 052aa7ec5d6ee482e2ef73c6475e5c931e5a7d3f
Author: B V HITESH SAI <[email protected]>
AuthorDate: Thu Nov 5 23:19:59 2026 +0530

    Add PluginManager API and Realm for scoped plugin service discovery (#13625)
    
    * Add scoped plugin service discovery API
    
    Expose a Maven 4 PluginManager service that resolves declared project 
plugins into public runtime metadata and performs component lookups with the 
plugin realm as the context classloader.
    
    This removes the need for build extensions to combine internal plugin 
manager and container APIs for plugin-contributed services.
    
    * Introduce scoped plugin realms
    
    Replace direct plugin classloader access with a PluginRealm that exposes 
the classloader, an optional module layer, and a realm-scoped Lookup.
    
    Keep TCCL management inside the Lookup implementation so callers cannot 
accidentally perform an unscoped component lookup.
    
    * Address plugin realm API review feedback
    
    Use Maven 4 noun-style realm accessors, document the new API, and preserve 
undeclared-plugin errors. Add the requested exception constructors and 
serialization metadata, nullable annotation, and regression coverage.
    
    * Document undeclared plugin error
    
    Declare the IllegalArgumentException thrown by PluginManager.loadPlugin 
when the requested plugin is not present in the project build.
    
    * Rename PluginRealm to Realm
    
    Generalize the interface for use at all levels (session, project,
    plugin). The same Realm shape — classLoader(), moduleLayer(), lookup()
    — applies uniformly; the difference is what the Lookup sees, not the
    type. Module layers are not plugin-specific (extensions and core can
    also use them, e.g. JLine per #13491).
    
    See #13223 (Layer 0b) for the design rationale.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Clarify realm lookup visibility contract
    
    Document that realm lookup delegates with the realm classloader as the TCCL 
and that component visibility depends on container filtering.
    
    * Handle plugin descriptors without class realms
    
    Use the current context classloader, with the Maven implementation 
classloader as a final fallback, when legacy descriptors have no realm 
attached. Restore regression coverage for minimal mojo descriptors used by 
expression evaluation.
    
    * fix: keep getClassLoader() as default delegating to 
getRealm().classLoader()
    
    getClassLoader() was part of the Plugin API since 4.0.0-alpha-10 (MNG-7947).
    Keep it as a default method delegating to getRealm().classLoader() to
    preserve backward compatibility.
    
    ---------
    
    Co-authored-by: Guillaume Nodet <[email protected]>
    Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
---
 .../src/main/java/org/apache/maven/api/Plugin.java |  13 +-
 .../src/main/java/org/apache/maven/api/Realm.java  |  61 +++++++
 .../apache/maven/api/services/PluginManager.java   |  51 ++++++
 .../maven/api/services/PluginManagerException.java |  43 +++++
 .../maven/internal/impl/DefaultMojoExecution.java  |  90 +---------
 .../apache/maven/internal/impl/DefaultPlugin.java  | 130 +++++++++++++++
 .../maven/internal/impl/DefaultPluginManager.java  | 100 +++++++++++
 .../apache/maven/internal/impl/DefaultRealm.java   | 113 +++++++++++++
 .../internal/impl/DefaultMojoExecutionTest.java    |   7 +
 .../internal/impl/DefaultPluginManagerTest.java    | 185 +++++++++++++++++++++
 .../maven/testing/plugin/stubs/PluginStub.java     |  30 +++-
 11 files changed, 731 insertions(+), 92 deletions(-)

diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/Plugin.java 
b/api/maven-api-core/src/main/java/org/apache/maven/api/Plugin.java
index 356ec1fe18..84e1c517e8 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/Plugin.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/Plugin.java
@@ -60,13 +60,24 @@ public interface Plugin {
     @Nonnull
     List<Lifecycle> getLifecycles();
 
+    /**
+     * Returns the runtime realm for this plugin.
+     *
+     * @return the plugin realm, never {@code null}
+     * @since 4.1.0
+     */
+    @Nonnull
+    Realm getRealm();
+
     /**
      * Returns the class loader used to load this plugin's classes.
      *
      * @return the class loader, never {@code null}
      */
     @Nonnull
-    ClassLoader getClassLoader();
+    default ClassLoader getClassLoader() {
+        return getRealm().classLoader();
+    }
 
     /**
      * Returns the artifact for this plugin.
diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/Realm.java 
b/api/maven-api-core/src/main/java/org/apache/maven/api/Realm.java
new file mode 100644
index 0000000000..930849aa9f
--- /dev/null
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/Realm.java
@@ -0,0 +1,61 @@
+/*
+ * 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.api;
+
+import java.util.Optional;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.services.Lookup;
+
+/**
+ * A runtime scope that bundles classloading information with component lookup.
+ * Lookup operations run with this realm's classloader set as the thread 
context classloader.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+public interface Realm {
+
+    /**
+     * Returns the classloader for this realm.
+     *
+     * @return the classloader, never {@code null}
+     */
+    @Nonnull
+    ClassLoader classLoader();
+
+    /**
+     * Returns the JPMS module layer when this realm runs in a modular 
configuration.
+     *
+     * @return the module layer, or an empty optional for a classpath-based 
realm
+     */
+    @Nonnull
+    Optional<ModuleLayer> moduleLayer();
+
+    /**
+     * Returns component lookup that delegates to the container with this 
realm's
+     * classloader set as the thread context classloader. The visibility of 
discovered
+     * components depends on the container's TCCL-based filtering behavior.
+     *
+     * @return the realm-aware component lookup, never {@code null}
+     */
+    @Nonnull
+    Lookup lookup();
+}
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/services/PluginManager.java
 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/PluginManager.java
new file mode 100644
index 0000000000..47c1ace9d9
--- /dev/null
+++ 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/PluginManager.java
@@ -0,0 +1,51 @@
+/*
+ * 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.api.services;
+
+import org.apache.maven.api.Plugin;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Service;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+
+/**
+ * Provides access to plugin runtimes and the services contributed by them.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+public interface PluginManager extends Service {
+
+    /**
+     * Resolves a plugin, creates its classloader when necessary, and returns 
its runtime metadata.
+     * The returned plugin exposes its descriptor, resolved dependencies, 
artifact, and runtime realm.
+     *
+     * @param session the session in which to resolve the plugin
+     * @param project the project declaring the plugin
+     * @param plugin the plugin declaration from the project's model
+     * @return the resolved plugin runtime
+     * @throws PluginManagerException if the plugin cannot be resolved or 
loaded
+     * @throws IllegalArgumentException if the plugin is not declared by the 
given project
+     * @throws NullPointerException if any argument is {@code null}
+     */
+    @Nonnull
+    Plugin loadPlugin(
+            @Nonnull Session session, @Nonnull Project project, @Nonnull 
org.apache.maven.api.model.Plugin plugin);
+}
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/services/PluginManagerException.java
 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/PluginManagerException.java
new file mode 100644
index 0000000000..5b27024198
--- /dev/null
+++ 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/PluginManagerException.java
@@ -0,0 +1,43 @@
+/*
+ * 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.api.services;
+
+import java.io.Serial;
+
+import org.apache.maven.api.annotations.Experimental;
+
+/**
+ * Thrown when a plugin runtime cannot be resolved or loaded.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+public class PluginManagerException extends MavenException {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    public PluginManagerException(String message) {
+        super(message);
+    }
+
+    public PluginManagerException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMojoExecution.java
 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMojoExecution.java
index 1483884942..fe7d61694b 100644
--- 
a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMojoExecution.java
+++ 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultMojoExecution.java
@@ -18,29 +18,15 @@
  */
 package org.apache.maven.internal.impl;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
-import java.util.stream.Collectors;
 
-import org.apache.maven.RepositoryUtils;
-import org.apache.maven.api.Artifact;
-import org.apache.maven.api.Dependency;
 import org.apache.maven.api.MojoExecution;
-import org.apache.maven.api.Node;
 import org.apache.maven.api.Plugin;
 import org.apache.maven.api.model.PluginExecution;
 import org.apache.maven.api.plugin.descriptor.MojoDescriptor;
-import org.apache.maven.api.plugin.descriptor.PluginDescriptor;
-import org.apache.maven.api.plugin.descriptor.lifecycle.Lifecycle;
+import org.apache.maven.api.services.Lookup;
 import org.apache.maven.api.xml.XmlNode;
-import org.apache.maven.impl.DefaultNode;
-import org.eclipse.aether.graph.DependencyNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 import static java.util.Objects.requireNonNull;
 
@@ -52,8 +38,6 @@
  */
 public class DefaultMojoExecution implements MojoExecution {
 
-    private static final Logger LOGGER = 
LoggerFactory.getLogger(DefaultMojoExecution.class);
-
     private final Plugin plugin;
     private final Optional<PluginExecution> model;
     private final MojoDescriptor descriptor;
@@ -81,76 +65,8 @@ private static Plugin buildPlugin(InternalMavenSession 
session, org.apache.maven
         org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = 
delegate.getMojoDescriptor();
         org.apache.maven.plugin.descriptor.PluginDescriptor 
legacyPluginDescriptor =
                 legacyDescriptor.getPluginDescriptor();
-        PluginDescriptor pluginDescriptorV4 = 
legacyPluginDescriptor.getPluginDescriptorV4();
-
-        ClassLoader classLoader = legacyDescriptor.getRealm();
-
-        org.apache.maven.artifact.Artifact legacyArtifact = 
legacyPluginDescriptor.getPluginArtifact();
-        org.eclipse.aether.artifact.Artifact resolverArtifact = 
RepositoryUtils.toArtifact(legacyArtifact);
-        Artifact artifact = resolverArtifact != null ? 
session.getArtifact(resolverArtifact) : null;
-
-        DependencyNode resolverNode = 
legacyPluginDescriptor.getDependencyNode();
-        Map<String, Dependency> dependenciesMap = resolverNode != null
-                ? Collections.unmodifiableMap(new DefaultNode(session, 
resolverNode, false)
-                        .stream()
-                                .filter(Objects::nonNull)
-                                .map(Node::getDependency)
-                                .filter(Objects::nonNull)
-                                .collect(Collectors.toMap(
-                                        d -> d.getGroupId() + ":" + 
d.getArtifactId(),
-                                        d -> d,
-                                        (a, b) -> a))) // first-wins on 
duplicate groupId:artifactId
-                // (transitive duplicates are normal)
-                : Collections.emptyMap();
-
-        org.apache.maven.api.model.Plugin modelPlugin =
-                delegate.getPlugin() != null ? 
delegate.getPlugin().getDelegate() : null;
-
-        // Eagerly capture lifecycle mappings so the Plugin snapshot is truly 
immutable.
-        // getLifecycleMappings() reads from the plugin JAR; plugins that do 
not bundle
-        // custom lifecycle metadata will throw here — fall back to an empty 
list.
-        List<Lifecycle> lifecycles;
-        try {
-            lifecycles = Collections.unmodifiableList(new ArrayList<>(
-                    legacyPluginDescriptor.getLifecycleMappings().values()));
-        } catch (Exception e) {
-            LOGGER.debug(
-                    "Unable to load lifecycle mappings for {}: {}", 
legacyPluginDescriptor.getId(), e.getMessage());
-            lifecycles = Collections.emptyList();
-        }
-        final List<Lifecycle> snapshotLifecycles = lifecycles;
-
-        return new Plugin() {
-            @Override
-            public org.apache.maven.api.model.Plugin getModel() {
-                return modelPlugin;
-            }
-
-            @Override
-            public PluginDescriptor getDescriptor() {
-                return pluginDescriptorV4;
-            }
-
-            @Override
-            public List<Lifecycle> getLifecycles() {
-                return snapshotLifecycles;
-            }
-
-            @Override
-            public ClassLoader getClassLoader() {
-                return classLoader;
-            }
-
-            @Override
-            public Artifact getArtifact() {
-                return artifact;
-            }
-
-            @Override
-            public Map<String, Dependency> getDependenciesMap() {
-                return dependenciesMap;
-            }
-        };
+        return new DefaultPlugin(
+                session, delegate.getPlugin(), legacyPluginDescriptor, 
session.getService(Lookup.class));
     }
 
     private static Optional<PluginExecution> 
buildModel(org.apache.maven.plugin.MojoExecution delegate) {
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPlugin.java
 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPlugin.java
new file mode 100644
index 0000000000..5dee8be9f1
--- /dev/null
+++ 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPlugin.java
@@ -0,0 +1,130 @@
+/*
+ * 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.internal.impl;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+import org.apache.maven.RepositoryUtils;
+import org.apache.maven.api.Artifact;
+import org.apache.maven.api.Dependency;
+import org.apache.maven.api.Node;
+import org.apache.maven.api.Plugin;
+import org.apache.maven.api.Realm;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.descriptor.PluginDescriptor;
+import org.apache.maven.api.plugin.descriptor.lifecycle.Lifecycle;
+import org.apache.maven.api.services.Lookup;
+import org.apache.maven.impl.DefaultNode;
+import org.eclipse.aether.graph.DependencyNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.util.Objects.requireNonNull;
+
+final class DefaultPlugin implements Plugin {
+
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(DefaultPlugin.class);
+
+    private final org.apache.maven.api.model.Plugin model;
+    private final PluginDescriptor descriptor;
+    private final List<Lifecycle> lifecycles;
+    private final Realm realm;
+    private final Artifact artifact;
+    private final Map<String, Dependency> dependencies;
+
+    DefaultPlugin(
+            InternalMavenSession session,
+            @Nullable org.apache.maven.model.Plugin model,
+            org.apache.maven.plugin.descriptor.PluginDescriptor descriptor,
+            Lookup lookup) {
+        requireNonNull(session, "session");
+        requireNonNull(descriptor, "descriptor");
+
+        this.model = model != null ? model.getDelegate() : null;
+        this.descriptor = requireNonNull(descriptor.getPluginDescriptorV4(), 
"descriptor.pluginDescriptorV4");
+        ClassLoader classLoader = descriptor.getClassRealm();
+        if (classLoader == null) {
+            classLoader = Thread.currentThread().getContextClassLoader();
+        }
+        if (classLoader == null) {
+            classLoader = DefaultPlugin.class.getClassLoader();
+        }
+        this.realm = new DefaultRealm(classLoader, lookup);
+
+        org.apache.maven.artifact.Artifact legacyArtifact = 
descriptor.getPluginArtifact();
+        org.eclipse.aether.artifact.Artifact resolverArtifact = 
RepositoryUtils.toArtifact(legacyArtifact);
+        this.artifact = resolverArtifact != null ? 
session.getArtifact(resolverArtifact) : null;
+
+        DependencyNode resolverNode = descriptor.getDependencyNode();
+        this.dependencies = resolverNode != null
+                ? Collections.unmodifiableMap(new DefaultNode(session, 
resolverNode, false)
+                        .stream()
+                                .filter(Objects::nonNull)
+                                .map(Node::getDependency)
+                                .filter(Objects::nonNull)
+                                .collect(Collectors.toMap(
+                                        d -> d.getGroupId() + ":" + 
d.getArtifactId(), d -> d, (a, b) -> a)))
+                : Collections.emptyMap();
+
+        List<Lifecycle> lifecycleMappings;
+        try {
+            lifecycleMappings = Collections.unmodifiableList(
+                    new 
ArrayList<>(descriptor.getLifecycleMappings().values()));
+        } catch (Exception e) {
+            LOGGER.debug("Unable to load lifecycle mappings for {}: {}", 
descriptor.getId(), e.getMessage());
+            lifecycleMappings = Collections.emptyList();
+        }
+        this.lifecycles = lifecycleMappings;
+    }
+
+    @Override
+    public org.apache.maven.api.model.Plugin getModel() {
+        return model;
+    }
+
+    @Override
+    public PluginDescriptor getDescriptor() {
+        return descriptor;
+    }
+
+    @Override
+    public List<Lifecycle> getLifecycles() {
+        return lifecycles;
+    }
+
+    @Override
+    public Realm getRealm() {
+        return realm;
+    }
+
+    @Override
+    public Artifact getArtifact() {
+        return artifact;
+    }
+
+    @Override
+    public Map<String, Dependency> getDependenciesMap() {
+        return dependencies;
+    }
+}
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPluginManager.java
 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPluginManager.java
new file mode 100644
index 0000000000..c7a41d54df
--- /dev/null
+++ 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultPluginManager.java
@@ -0,0 +1,100 @@
+/*
+ * 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.internal.impl;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.inject.Singleton;
+
+import java.util.Objects;
+
+import org.apache.maven.api.Plugin;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.services.Lookup;
+import org.apache.maven.api.services.PluginManager;
+import org.apache.maven.api.services.PluginManagerException;
+import org.apache.maven.execution.MavenSession;
+import org.apache.maven.lifecycle.internal.LifecyclePluginResolver;
+import org.apache.maven.plugin.MavenPluginManager;
+import org.apache.maven.plugin.descriptor.PluginDescriptor;
+import org.apache.maven.plugin.version.PluginVersionResolutionException;
+import org.apache.maven.project.MavenProject;
+
+import static java.util.Objects.requireNonNull;
+import static org.apache.maven.internal.impl.CoreUtils.cast;
+
+@Named
+@Singleton
+public final class DefaultPluginManager implements PluginManager {
+
+    private final MavenPluginManager pluginManager;
+    private final LifecyclePluginResolver lifecyclePluginResolver;
+    private final Lookup lookup;
+
+    @Inject
+    public DefaultPluginManager(
+            MavenPluginManager pluginManager, LifecyclePluginResolver 
lifecyclePluginResolver, Lookup lookup) {
+        this.pluginManager = requireNonNull(pluginManager, "pluginManager");
+        this.lifecyclePluginResolver = requireNonNull(lifecyclePluginResolver, 
"lifecyclePluginResolver");
+        this.lookup = requireNonNull(lookup, "lookup");
+    }
+
+    @Override
+    public Plugin loadPlugin(Session session, Project project, 
org.apache.maven.api.model.Plugin plugin) {
+        requireNonNull(session, "session");
+        requireNonNull(project, "project");
+        requireNonNull(plugin, "plugin");
+
+        InternalMavenSession internalSession = 
InternalMavenSession.from(session);
+        MavenProject mavenProject =
+                cast(DefaultProject.class, project, "project").getProject();
+        MavenSession executionSession = 
internalSession.getMavenSession().clone();
+        executionSession.setCurrentProject(mavenProject);
+
+        try {
+            lifecyclePluginResolver.resolveMissingPluginVersions(mavenProject, 
executionSession);
+        } catch (PluginVersionResolutionException e) {
+            throw new PluginManagerException(
+                    "Unable to resolve plugin " + plugin.getGroupId() + ":" + 
plugin.getArtifactId(), e);
+        }
+
+        org.apache.maven.model.Plugin legacyPlugin = findPlugin(mavenProject, 
plugin);
+
+        try {
+            PluginDescriptor descriptor = pluginManager.getPluginDescriptor(
+                    legacyPlugin, mavenProject.getRemotePluginRepositories(), 
executionSession.getRepositorySession());
+            pluginManager.setupPluginRealm(descriptor, executionSession, null, 
null, null);
+            return new DefaultPlugin(internalSession, legacyPlugin, 
descriptor, lookup);
+        } catch (Exception e) {
+            throw new PluginManagerException(
+                    "Unable to load plugin " + plugin.getGroupId() + ":" + 
plugin.getArtifactId(), e);
+        }
+    }
+
+    private org.apache.maven.model.Plugin findPlugin(
+            MavenProject project, org.apache.maven.api.model.Plugin 
requestedPlugin) {
+        return project.getBuildPlugins().stream()
+                .filter(candidate -> Objects.equals(candidate.getGroupId(), 
requestedPlugin.getGroupId())
+                        && Objects.equals(candidate.getArtifactId(), 
requestedPlugin.getArtifactId()))
+                .findFirst()
+                .orElseThrow(() -> new IllegalArgumentException("Plugin " + 
requestedPlugin.getGroupId() + ":"
+                        + requestedPlugin.getArtifactId() + " is not declared 
by project " + project.getId()));
+    }
+}
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRealm.java
 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRealm.java
new file mode 100644
index 0000000000..8241e9f88f
--- /dev/null
+++ 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultRealm.java
@@ -0,0 +1,113 @@
+/*
+ * 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.internal.impl;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Supplier;
+
+import org.apache.maven.api.Realm;
+import org.apache.maven.api.services.Lookup;
+
+import static java.util.Objects.requireNonNull;
+
+final class DefaultRealm implements Realm {
+
+    private final ClassLoader classLoader;
+    private final Optional<ModuleLayer> moduleLayer;
+    private final Lookup lookup;
+
+    DefaultRealm(ClassLoader classLoader, Lookup lookup) {
+        this(classLoader, null, lookup);
+    }
+
+    DefaultRealm(ClassLoader classLoader, ModuleLayer moduleLayer, Lookup 
lookup) {
+        this.classLoader = requireNonNull(classLoader, "classLoader");
+        this.moduleLayer = Optional.ofNullable(moduleLayer);
+        this.lookup = new RealmLookup(classLoader, requireNonNull(lookup, 
"lookup"));
+    }
+
+    @Override
+    public ClassLoader classLoader() {
+        return classLoader;
+    }
+
+    @Override
+    public Optional<ModuleLayer> moduleLayer() {
+        return moduleLayer;
+    }
+
+    @Override
+    public Lookup lookup() {
+        return lookup;
+    }
+
+    private static final class RealmLookup implements Lookup {
+
+        private final ClassLoader classLoader;
+        private final Lookup delegate;
+
+        private RealmLookup(ClassLoader classLoader, Lookup delegate) {
+            this.classLoader = classLoader;
+            this.delegate = delegate;
+        }
+
+        @Override
+        public <T> T lookup(Class<T> type) {
+            return scoped(() -> delegate.lookup(type));
+        }
+
+        @Override
+        public <T> T lookup(Class<T> type, String name) {
+            return scoped(() -> delegate.lookup(type, name));
+        }
+
+        @Override
+        public <T> Optional<T> lookupOptional(Class<T> type) {
+            return scoped(() -> delegate.lookupOptional(type));
+        }
+
+        @Override
+        public <T> Optional<T> lookupOptional(Class<T> type, String name) {
+            return scoped(() -> delegate.lookupOptional(type, name));
+        }
+
+        @Override
+        public <T> List<T> lookupList(Class<T> type) {
+            return scoped(() -> delegate.lookupList(type));
+        }
+
+        @Override
+        public <T> Map<String, T> lookupMap(Class<T> type) {
+            return scoped(() -> delegate.lookupMap(type));
+        }
+
+        private <T> T scoped(Supplier<T> action) {
+            Thread thread = Thread.currentThread();
+            ClassLoader originalClassLoader = thread.getContextClassLoader();
+            try {
+                thread.setContextClassLoader(classLoader);
+                return action.get();
+            } finally {
+                thread.setContextClassLoader(originalClassLoader);
+            }
+        }
+    }
+}
diff --git 
a/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultMojoExecutionTest.java
 
b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultMojoExecutionTest.java
index 2364d53348..e4591fe327 100644
--- 
a/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultMojoExecutionTest.java
+++ 
b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultMojoExecutionTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.maven.internal.impl;
 
+import org.apache.maven.api.services.Lookup;
 import org.apache.maven.plugin.MojoExecution;
 import org.apache.maven.plugin.descriptor.MojoDescriptor;
 import org.apache.maven.plugin.descriptor.PluginDescriptor;
@@ -25,8 +26,10 @@
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 /**
  * Tests for {@link DefaultMojoExecution} immutable snapshot semantics.
@@ -76,6 +79,7 @@ private static MojoExecution lifecycleExecution(String goal, 
String executionId,
     @Test
     void cliInvocationPathExecutionIdAndLifecyclePhaseAreEmpty() {
         InternalMavenSession session = mock(InternalMavenSession.class);
+        when(session.getService(Lookup.class)).thenReturn(mock(Lookup.class));
         MojoExecution delegate = cliExecution("help");
 
         org.apache.maven.api.MojoExecution snapshot = new 
DefaultMojoExecution(session, delegate);
@@ -85,11 +89,13 @@ void 
cliInvocationPathExecutionIdAndLifecyclePhaseAreEmpty() {
         assertFalse(snapshot.lifecyclePhase().isPresent(), "lifecyclePhase 
should be empty for CLI invocation");
         assertFalse(snapshot.model().isPresent(), "model should be empty when 
no plugin in model");
         assertFalse(snapshot.configuration().isPresent(), "configuration 
should be empty when not set");
+        assertNotNull(snapshot.plugin().getRealm().classLoader());
     }
 
     @Test
     void 
lifecycleBoundExecutionExecutionIdAndLifecyclePhasePresentAndImmutable() {
         InternalMavenSession session = mock(InternalMavenSession.class);
+        when(session.getService(Lookup.class)).thenReturn(mock(Lookup.class));
         MojoExecution delegate = lifecycleExecution("compile", 
"default-compile", "compile");
 
         org.apache.maven.api.MojoExecution snapshot = new 
DefaultMojoExecution(session, delegate);
@@ -108,6 +114,7 @@ void 
lifecycleBoundExecutionExecutionIdAndLifecyclePhasePresentAndImmutable() {
     @Test
     void snapshotDescriptorMatchesLegacyDescriptor() {
         InternalMavenSession session = mock(InternalMavenSession.class);
+        when(session.getService(Lookup.class)).thenReturn(mock(Lookup.class));
         MojoExecution delegate = cliExecution("clean");
 
         org.apache.maven.api.MojoExecution snapshot = new 
DefaultMojoExecution(session, delegate);
diff --git 
a/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultPluginManagerTest.java
 
b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultPluginManagerTest.java
new file mode 100644
index 0000000000..28e95cbc2e
--- /dev/null
+++ 
b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultPluginManagerTest.java
@@ -0,0 +1,185 @@
+/*
+ * 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.internal.impl;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import org.apache.maven.api.Plugin;
+import org.apache.maven.api.services.Lookup;
+import org.apache.maven.execution.MavenSession;
+import org.apache.maven.lifecycle.internal.LifecyclePluginResolver;
+import org.apache.maven.model.Build;
+import org.apache.maven.plugin.MavenPluginManager;
+import org.apache.maven.plugin.descriptor.PluginDescriptor;
+import org.apache.maven.project.MavenProject;
+import org.codehaus.plexus.classworlds.realm.ClassRealm;
+import org.eclipse.aether.graph.DependencyNode;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+class DefaultPluginManagerTest {
+
+    @Test
+    void loadsPluginRuntimeForProjectDeclaration() throws Exception {
+        MavenPluginManager legacyPluginManager = 
mock(MavenPluginManager.class);
+        LifecyclePluginResolver lifecyclePluginResolver = 
mock(LifecyclePluginResolver.class);
+        Lookup lookup = mock(Lookup.class);
+        InternalMavenSession session = mock(InternalMavenSession.class);
+        MavenSession mavenSession = mock(MavenSession.class);
+        MavenSession executionSession = mock(MavenSession.class);
+        DefaultProject project = mock(DefaultProject.class);
+        MavenProject mavenProject = new MavenProject();
+        Build build = new Build();
+        org.apache.maven.model.Plugin model = new 
org.apache.maven.model.Plugin();
+        model.setGroupId("org.example");
+        model.setArtifactId("example-plugin");
+        model.setVersion("1.0");
+        build.addPlugin(model);
+        mavenProject.setBuild(build);
+
+        PluginDescriptor descriptor = mock(PluginDescriptor.class);
+        org.apache.maven.api.plugin.descriptor.PluginDescriptor apiDescriptor =
+                
mock(org.apache.maven.api.plugin.descriptor.PluginDescriptor.class);
+        ClassRealm realm = mock(ClassRealm.class);
+        DependencyNode dependencyNode = mock(DependencyNode.class);
+        org.eclipse.aether.graph.Dependency resolverDependency = 
mock(org.eclipse.aether.graph.Dependency.class);
+        org.apache.maven.api.Dependency dependency = 
mock(org.apache.maven.api.Dependency.class);
+
+        when(session.getMavenSession()).thenReturn(mavenSession);
+        when(mavenSession.clone()).thenReturn(executionSession);
+        when(project.getProject()).thenReturn(mavenProject);
+        when(legacyPluginManager.getPluginDescriptor(eq(model), any(), 
any())).thenReturn(descriptor);
+        when(descriptor.getPluginDescriptorV4()).thenReturn(apiDescriptor);
+        when(descriptor.getClassRealm()).thenReturn(realm);
+        when(descriptor.getDependencyNode()).thenReturn(dependencyNode);
+        when(dependencyNode.getDependency()).thenReturn(resolverDependency);
+        when(dependencyNode.getChildren()).thenReturn(List.of());
+        when(session.getDependency(resolverDependency)).thenReturn(dependency);
+        when(dependency.getGroupId()).thenReturn("org.example");
+        when(dependency.getArtifactId()).thenReturn("plugin-spi");
+
+        DefaultPluginManager manager = new 
DefaultPluginManager(legacyPluginManager, lifecyclePluginResolver, lookup);
+
+        Plugin result = manager.loadPlugin(session, project, 
model.getDelegate());
+
+        assertSame(model.getDelegate(), result.getModel());
+        assertSame(apiDescriptor, result.getDescriptor());
+        assertSame(realm, result.getRealm().classLoader());
+        assertEquals(Optional.empty(), result.getRealm().moduleLayer());
+        assertEquals(List.of(dependency), 
result.getDependencies().stream().toList());
+        assertSame(dependency, 
result.getDependenciesMap().get("org.example:plugin-spi"));
+        verify(executionSession).setCurrentProject(mavenProject);
+        
verify(lifecyclePluginResolver).resolveMissingPluginVersions(mavenProject, 
executionSession);
+        verify(legacyPluginManager).setupPluginRealm(descriptor, 
executionSession, null, null, null);
+    }
+
+    @Test
+    void preservesUndeclaredPluginError() throws Exception {
+        MavenPluginManager legacyPluginManager = 
mock(MavenPluginManager.class);
+        LifecyclePluginResolver lifecyclePluginResolver = 
mock(LifecyclePluginResolver.class);
+        InternalMavenSession session = mock(InternalMavenSession.class);
+        MavenSession mavenSession = mock(MavenSession.class);
+        MavenSession executionSession = mock(MavenSession.class);
+        DefaultProject project = mock(DefaultProject.class);
+        MavenProject mavenProject = new MavenProject();
+        Build build = new Build();
+        org.apache.maven.model.Plugin model = new 
org.apache.maven.model.Plugin();
+        model.setGroupId("org.example");
+        model.setArtifactId("missing-plugin");
+        mavenProject.setGroupId("org.example");
+        mavenProject.setArtifactId("example-project");
+        mavenProject.setVersion("1.0");
+        mavenProject.setBuild(build);
+
+        when(session.getMavenSession()).thenReturn(mavenSession);
+        when(mavenSession.clone()).thenReturn(executionSession);
+        when(project.getProject()).thenReturn(mavenProject);
+
+        DefaultPluginManager manager =
+                new DefaultPluginManager(legacyPluginManager, 
lifecyclePluginResolver, mock(Lookup.class));
+
+        IllegalArgumentException failure = assertThrows(
+                IllegalArgumentException.class, () -> 
manager.loadPlugin(session, project, model.getDelegate()));
+
+        assertEquals(
+                "Plugin org.example:missing-plugin is not declared by project 
" + mavenProject.getId(),
+                failure.getMessage());
+        
verify(lifecyclePluginResolver).resolveMissingPluginVersions(mavenProject, 
executionSession);
+        verifyNoInteractions(legacyPluginManager);
+    }
+
+    @Test
+    void looksUpComponentsWithPluginClassLoaderAndRestoresOriginal() {
+        ClassLoader pluginClassLoader = new ClassLoader() {};
+        ClassLoader originalClassLoader = 
Thread.currentThread().getContextClassLoader();
+        Object service = new Object();
+        Lookup lookup = mock(Lookup.class, invocation -> {
+            assertSame(pluginClassLoader, 
Thread.currentThread().getContextClassLoader());
+            return switch (invocation.getMethod().getName()) {
+                case "lookup" -> service;
+                case "lookupOptional" -> Optional.of(service);
+                case "lookupList" -> List.of(service);
+                case "lookupMap" -> Map.of("service", service);
+                default -> throw new AssertionError(invocation.getMethod());
+            };
+        });
+        DefaultRealm realm = new DefaultRealm(pluginClassLoader, lookup);
+
+        assertSame(service, realm.lookup().lookup(Object.class));
+        assertSame(service, realm.lookup().lookup(Object.class, "service"));
+        assertEquals(Optional.of(service), 
realm.lookup().lookupOptional(Object.class));
+        assertEquals(Optional.of(service), 
realm.lookup().lookupOptional(Object.class, "service"));
+        assertEquals(List.of(service), 
realm.lookup().lookupList(Object.class));
+        assertEquals(Map.of("service", service), 
realm.lookup().lookupMap(Object.class));
+        assertSame(originalClassLoader, 
Thread.currentThread().getContextClassLoader());
+    }
+
+    @Test
+    void restoresOriginalClassLoaderWhenLookupFails() {
+        Lookup lookup = mock(Lookup.class);
+        ClassLoader pluginClassLoader = new ClassLoader() {};
+        ClassLoader originalClassLoader = 
Thread.currentThread().getContextClassLoader();
+        IllegalStateException failure = new IllegalStateException("boom");
+
+        doAnswer(invocation -> {
+                    assertSame(pluginClassLoader, 
Thread.currentThread().getContextClassLoader());
+                    throw failure;
+                })
+                .when(lookup)
+                .lookupList(Object.class);
+        DefaultRealm realm = new DefaultRealm(pluginClassLoader, lookup);
+
+        assertSame(
+                failure,
+                assertThrows(IllegalStateException.class, () -> 
realm.lookup().lookupList(Object.class)));
+        assertSame(originalClassLoader, 
Thread.currentThread().getContextClassLoader());
+    }
+}
diff --git 
a/impl/maven-testing/src/main/java/org/apache/maven/testing/plugin/stubs/PluginStub.java
 
b/impl/maven-testing/src/main/java/org/apache/maven/testing/plugin/stubs/PluginStub.java
index 026cf373d6..eb7bafb60d 100644
--- 
a/impl/maven-testing/src/main/java/org/apache/maven/testing/plugin/stubs/PluginStub.java
+++ 
b/impl/maven-testing/src/main/java/org/apache/maven/testing/plugin/stubs/PluginStub.java
@@ -21,12 +21,15 @@
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 
 import org.apache.maven.api.Artifact;
 import org.apache.maven.api.Dependency;
 import org.apache.maven.api.Plugin;
+import org.apache.maven.api.Realm;
 import org.apache.maven.api.plugin.descriptor.PluginDescriptor;
 import org.apache.maven.api.plugin.descriptor.lifecycle.Lifecycle;
+import org.apache.maven.api.services.Lookup;
 
 /**
  * A stub implementation of {@link Plugin} for testing Maven plugins.
@@ -52,7 +55,7 @@ public class PluginStub implements Plugin {
     org.apache.maven.api.model.Plugin model;
     PluginDescriptor descriptor;
     List<Lifecycle> lifecycles = Collections.emptyList();
-    ClassLoader classLoader;
+    Realm realm;
     Artifact artifact;
     List<Dependency> dependencies = Collections.emptyList();
     Map<String, Dependency> dependenciesMap = Collections.emptyMap();
@@ -85,12 +88,31 @@ public void setLifecycles(List<Lifecycle> lifecycles) {
     }
 
     @Override
-    public ClassLoader getClassLoader() {
-        return classLoader;
+    public Realm getRealm() {
+        return realm;
     }
 
     public void setClassLoader(ClassLoader classLoader) {
-        this.classLoader = classLoader;
+        this.realm = new Realm() {
+            @Override
+            public ClassLoader classLoader() {
+                return classLoader;
+            }
+
+            @Override
+            public Optional<ModuleLayer> moduleLayer() {
+                return Optional.empty();
+            }
+
+            @Override
+            public Lookup lookup() {
+                return LookupStub.EMPTY;
+            }
+        };
+    }
+
+    public void setRealm(Realm realm) {
+        this.realm = realm;
     }
 
     @Override

Reply via email to