gnodet-bot commented on code in PR #14111:
URL: https://github.com/apache/maven/pull/14111#discussion_r4723320635


##########
impl/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedCompositeBeanHelper.java:
##########
@@ -0,0 +1,360 @@
+/*
+ * 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.configuration.internal;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import com.google.inject.TypeLiteral;
+import 
org.codehaus.plexus.component.configurator.ComponentConfigurationException;
+import org.codehaus.plexus.component.configurator.ConfigurationListener;
+import 
org.codehaus.plexus.component.configurator.converters.ConfigurationConverter;
+import 
org.codehaus.plexus.component.configurator.converters.ParameterizedConfigurationConverter;
+import 
org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup;
+import 
org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
+import org.codehaus.plexus.configuration.PlexusConfiguration;
+import org.eclipse.sisu.bean.DeclaredMembers;
+import org.eclipse.sisu.bean.DeclaredMembers.View;
+import org.eclipse.sisu.plexus.TypeArguments;
+
+/**
+ * Optimized version of CompositeBeanHelper with caching for improved 
performance.
+ * This implementation caches method and field lookups to avoid repeated 
reflection operations.
+ */
+public final class EnhancedCompositeBeanHelper {
+
+    // Cache for method lookups: Class -> PropertyName -> MethodInfo
+    private static final ConcurrentMap<Class<?>, Map<String, MethodInfo>> 
METHOD_CACHE = new ConcurrentHashMap<>();
+
+    // Cache for field lookups: Class -> FieldName -> Field
+    private static final ConcurrentMap<Class<?>, Map<String, Field>> 
FIELD_CACHE = new ConcurrentHashMap<>();
+
+    private final ConverterLookup lookup;
+    private final ClassLoader loader;
+    private final ExpressionEvaluator evaluator;
+    private final ConfigurationListener listener;
+
+    /**
+     * Holds information about a method including its parameter type.
+     */
+    private record MethodInfo(Method method, Type parameterType) {}
+
+    public EnhancedCompositeBeanHelper(
+            ConverterLookup lookup, ClassLoader loader, ExpressionEvaluator 
evaluator, ConfigurationListener listener) {
+        this.lookup = lookup;
+        this.loader = loader;
+        this.evaluator = evaluator;
+        this.listener = listener;
+    }
+
+    /**
+     * Calls the default "set" method on the bean; re-converts the 
configuration if necessary.
+     */
+    public void setDefault(Object bean, Object defaultValue, 
PlexusConfiguration configuration)
+            throws ComponentConfigurationException {
+
+        Class<?> beanType = bean.getClass();
+
+        // Find the default "set" method
+        MethodInfo setterInfo = findCachedMethod(beanType, "", null);
+        if (setterInfo == null) {
+            // Look for any method named "set" with one parameter
+            Map<String, MethodInfo> classMethodCache = 
METHOD_CACHE.computeIfAbsent(beanType, this::buildMethodCache);
+            setterInfo = classMethodCache.get("set");
+        }
+
+        if (setterInfo == null) {
+            throw new ComponentConfigurationException(configuration, "Cannot 
find default setter in " + beanType);
+        }
+
+        Object value = defaultValue;
+        TypeLiteral<?> paramType = TypeLiteral.get(setterInfo.parameterType);
+
+        if (!paramType.getRawType().isInstance(value)) {
+            if (configuration.getChildCount() > 0) {
+                throw new ComponentConfigurationException(
+                        "Basic element '" + configuration.getName() + "' must 
not contain child elements");
+            }
+            value = convertProperty(beanType, paramType.getRawType(), 
paramType.getType(), configuration);
+        }
+
+        if (value != null) {
+            try {
+                if (listener != null) {
+                    listener.notifyFieldChangeUsingSetter("", value, bean);
+                }
+                setterInfo.method.invoke(bean, value);
+            } catch (IllegalAccessException | InvocationTargetException | 
LinkageError e) {
+                throw new ComponentConfigurationException(configuration, 
"Cannot set default", e);
+            }
+        }
+    }
+
+    /**
+     * Converts a configured property without assigning it to the bean.
+     */
+    public Object getPropertyValue(
+            Class<?> beanType, String propertyName, Class<?> valueType, 
PlexusConfiguration configuration)
+            throws ComponentConfigurationException {
+
+        MethodInfo methodInfo = findCachedMethod(beanType, propertyName, 
valueType);
+
+        if (methodInfo != null) {
+            Object value = convertPropertyForMethod(beanType, methodInfo, 
valueType, configuration);
+            if (value != null) {
+                return value;
+            }
+        }
+
+        Field field = findCachedField(beanType, propertyName);
+        if (field != null) {
+            return convertPropertyForField(beanType, field, valueType, 
configuration);
+        }
+
+        if (methodInfo == null) {
+            throw new ComponentConfigurationException(
+                    configuration, "Cannot find '" + propertyName + "' in " + 
beanType);
+        }
+
+        return null;
+    }
+
+    /**
+     * Returns the declared type of a configured property without converting 
its value.
+     */
+    public Type getPropertyType(Class<?> beanType, String propertyName) {
+        MethodInfo methodInfo = findCachedMethod(beanType, propertyName, null);
+
+        if (methodInfo != null) {
+            return methodInfo.parameterType();
+        }
+
+        Field field = findCachedField(beanType, propertyName);
+        return field != null ? field.getGenericType() : null;
+    }
+
+    /**
+     * Sets a property in the bean using cached lookups for improved 
performance.
+     */
+    public void setProperty(Object bean, String propertyName, Class<?> 
valueType, PlexusConfiguration configuration)
+            throws ComponentConfigurationException {
+
+        Class<?> beanType = bean.getClass();
+
+        // Try setter/adder methods first
+        MethodInfo methodInfo = findCachedMethod(beanType, propertyName, 
valueType);
+        if (methodInfo != null) {
+            try {
+                Object value = convertPropertyForMethod(beanType, methodInfo, 
valueType, configuration);
+                if (value != null) {
+                    if (listener != null) {
+                        listener.notifyFieldChangeUsingSetter(propertyName, 
value, bean);
+                    }
+                    methodInfo.method.invoke(bean, value);
+                    return;
+                }
+            } catch (IllegalAccessException | InvocationTargetException | 
LinkageError e) {
+                // Fall through to field access
+            }
+        }
+
+        // Try field access
+        Field field = findCachedField(beanType, propertyName);
+        if (field != null) {
+            try {
+                Object value = convertPropertyForField(beanType, field, 
valueType, configuration);
+                if (value != null) {
+                    if (listener != null) {
+                        
listener.notifyFieldChangeUsingReflection(propertyName, value, bean);
+                    }
+                    setFieldValue(bean, field, value);
+                    return;
+                }
+            } catch (IllegalAccessException | LinkageError e) {
+                // Continue to error handling
+            }
+        }
+
+        // If we get here, we couldn't set the property
+        if (methodInfo == null && field == null) {
+            throw new ComponentConfigurationException(
+                    configuration, "Cannot find '" + propertyName + "' in " + 
beanType);
+        }
+    }
+
+    /**
+     * Find method using cache for improved performance.
+     */
+    private MethodInfo findCachedMethod(Class<?> beanType, String 
propertyName, Class<?> valueType) {
+        Map<String, MethodInfo> classMethodCache = 
METHOD_CACHE.computeIfAbsent(beanType, this::buildMethodCache);
+
+        String title = Character.toTitleCase(propertyName.charAt(0)) + 
propertyName.substring(1);

Review Comment:
   🔴 **`StringIndexOutOfBoundsException` when `propertyName` is `""`**: 
`setDefault()` on line 83 calls `findCachedMethod(beanType, "", null)`. When 
this reaches here, `propertyName.charAt(0)` throws 
`StringIndexOutOfBoundsException` before the fallback 
`classMethodCache.get("set")` in the caller (lines 85–87) is reached.
   
   ```suggestion
           if (propertyName.isEmpty()) {
               return classMethodCache.get("set");
           }
           String title = Character.toTitleCase(propertyName.charAt(0)) + 
propertyName.substring(1);
   ```



##########
impl/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedCompositeBeanHelper.java:
##########
@@ -0,0 +1,360 @@
+/*
+ * 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.configuration.internal;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import com.google.inject.TypeLiteral;
+import 
org.codehaus.plexus.component.configurator.ComponentConfigurationException;
+import org.codehaus.plexus.component.configurator.ConfigurationListener;
+import 
org.codehaus.plexus.component.configurator.converters.ConfigurationConverter;
+import 
org.codehaus.plexus.component.configurator.converters.ParameterizedConfigurationConverter;
+import 
org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup;
+import 
org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
+import org.codehaus.plexus.configuration.PlexusConfiguration;
+import org.eclipse.sisu.bean.DeclaredMembers;
+import org.eclipse.sisu.bean.DeclaredMembers.View;
+import org.eclipse.sisu.plexus.TypeArguments;
+
+/**
+ * Optimized version of CompositeBeanHelper with caching for improved 
performance.
+ * This implementation caches method and field lookups to avoid repeated 
reflection operations.
+ */
+public final class EnhancedCompositeBeanHelper {
+
+    // Cache for method lookups: Class -> PropertyName -> MethodInfo
+    private static final ConcurrentMap<Class<?>, Map<String, MethodInfo>> 
METHOD_CACHE = new ConcurrentHashMap<>();
+
+    // Cache for field lookups: Class -> FieldName -> Field
+    private static final ConcurrentMap<Class<?>, Map<String, Field>> 
FIELD_CACHE = new ConcurrentHashMap<>();

Review Comment:
   🔵 **Unbounded static cache**: `METHOD_CACHE` and `FIELD_CACHE` are static 
and never evicted. Each distinct mojo `Class<?>` from any plugin realm adds an 
entry that holds a strong reference to the `Class<?>` — keeping its 
`ClassLoader` (the plugin realm) alive indefinitely, preventing GC of the 
entire realm and all classes it loaded. `clearCaches()` exists for testing but 
is not called in production. Consider `WeakHashMap<Class<?>, ...>` 
(synchronized) or document the unbounded growth.



##########
impl/maven-core/src/main/java/org/apache/maven/configuration/internal/DefaultMojoConfigurationService.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.configuration.internal;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import java.lang.reflect.Type;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Service;
+import org.apache.maven.api.di.SessionScoped;
+import org.apache.maven.api.plugin.descriptor.Parameter;
+import org.apache.maven.api.services.MojoConfigurationService;
+import org.apache.maven.api.xml.XmlNode;
+import org.apache.maven.internal.impl.DefaultMojoExecution;
+import org.apache.maven.internal.impl.DefaultProject;
+import org.apache.maven.internal.impl.InternalMavenSession;
+import org.apache.maven.internal.xml.XmlPlexusConfiguration;
+import org.apache.maven.plugin.MavenPluginManager;
+import org.apache.maven.plugin.PluginContainerException;
+import org.apache.maven.plugin.PluginParameterExpressionEvaluator;
+import org.apache.maven.plugin.PluginParameterExpressionEvaluatorV4;
+import org.apache.maven.plugin.PluginResolutionException;
+import org.apache.maven.plugin.descriptor.PluginDescriptor;
+import org.codehaus.plexus.classworlds.realm.ClassRealm;
+import 
org.codehaus.plexus.component.configurator.ComponentConfigurationException;
+import 
org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
+import org.codehaus.plexus.configuration.DefaultPlexusConfiguration;
+import org.codehaus.plexus.configuration.PlexusConfiguration;
+import org.eclipse.sisu.Typed;
+
+@Named
+@Typed({MojoConfigurationService.class, Service.class})
+@SessionScoped
+public class DefaultMojoConfigurationService implements 
MojoConfigurationService {
+
+    private Object resolveParameterValue(
+            EnhancedCompositeBeanHelper helper,
+            Class<?> mojoClass,
+            String parameterName,
+            PlexusConfiguration configuration)
+            throws ComponentConfigurationException {
+
+        Type propertyType = helper.getPropertyType(mojoClass, parameterName);
+
+        if (MojoParameterType.isSafe(propertyType)) {
+            return helper.getPropertyValue(mojoClass, parameterName, null, 
configuration);
+        }
+
+        if (configuration instanceof XmlPlexusConfiguration xmlConfiguration) {
+            return xmlConfiguration.toXmlNode();
+        }
+
+        return XmlNode.newInstance(
+                configuration.getName(),
+                
configuration.getValue(configuration.getAttribute("default-value")),
+                null,
+                null,
+                null);
+    }
+
+    private final InternalMavenSession session;
+    private final MavenPluginManager pluginManager;
+
+    @Inject
+    public DefaultMojoConfigurationService(InternalMavenSession session, 
MavenPluginManager pluginManager) {
+        this.session = session;
+        this.pluginManager = pluginManager;
+    }
+
+    @Override
+    public Map<String, Object> getParameters(Project project, MojoExecution 
mojoExecution) {
+        if (!(mojoExecution instanceof DefaultMojoExecution execution)) {
+            throw new IllegalArgumentException("Unsupported MojoExecution 
implementation: "
+                    + mojoExecution.getClass().getName());
+        }
+
+        if (!(project instanceof DefaultProject defaultProject)) {
+            throw new IllegalArgumentException(
+                    "Unsupported Project implementation: " + 
project.getClass().getName());
+        }
+
+        org.apache.maven.project.MavenProject mavenProject = 
defaultProject.getProject();
+
+        org.apache.maven.plugin.MojoExecution delegate = 
execution.getDelegate();
+        org.apache.maven.plugin.descriptor.MojoDescriptor mojoDescriptor = 
delegate.getMojoDescriptor();
+
+        PluginDescriptor pluginDescriptor = 
mojoDescriptor.getPluginDescriptor();
+        org.apache.maven.execution.MavenSession interpolationSession =
+                session.getMavenSession().clone();
+        interpolationSession.setCurrentProject(mavenProject);
+        ClassRealm pluginRealm = pluginDescriptor.getClassRealm();
+
+        if (pluginRealm == null) {
+            try {
+                pluginManager.setupPluginRealm(pluginDescriptor, 
interpolationSession, null, null, null);
+                pluginRealm = pluginDescriptor.getClassRealm();

Review Comment:
   🟠 **Missing null guard**: if `setupPluginRealm` succeeds without registering 
a realm, `pluginRealm` is null here. `setContextClassLoader(null)` then 
silently clears the TCCL, and `Class.forName(..., false, null)` throws 
`ClassNotFoundException` with a misleading error message. Add an explicit check:
   
   ```suggestion
                   pluginRealm = pluginDescriptor.getClassRealm();
                   if (pluginRealm == null) {
                       throw new IllegalStateException(
                               "Plugin realm setup completed but no ClassRealm 
was registered for "
                                       + pluginDescriptor.getId());
                   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to