diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/services/MojoConfigurationService.java b/api/maven-api-core/src/main/java/org/apache/maven/api/services/MojoConfigurationService.java new file mode 100644 index 000000000000..e71772f9cd85 --- /dev/null +++ b/api/maven-api-core/src/main/java/org/apache/maven/api/services/MojoConfigurationService.java @@ -0,0 +1,71 @@ +/* + * 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.util.Map; + +import org.apache.maven.api.MojoExecution; +import org.apache.maven.api.Project; +import org.apache.maven.api.Service; +import org.apache.maven.api.annotations.Experimental; +import org.apache.maven.api.annotations.Nonnull; + +/** + * Provides access to the configured parameters of a Mojo without instantiating the root Mojo, invoking its setters, + * or running its {@code execute} method. Resolving parameters may require resolving the plugin and setting up its + * class realm. Converting nested configuration may instantiate nested parameter objects and invoke their setters. + * + * @since 4.2.0 + */ +@Experimental +public interface MojoConfigurationService extends Service { + + /** + * Resolves the configured parameters of a Mojo execution. + * + * Mojos using both the Maven 3 and Maven 4 APIs are supported. + * Plugin resolution may occur if the plugin realm has not already been set up. + * + * The root Mojo is not instantiated, its setters are not invoked, and its + * {@code execute} method is not run. Plugin-specific parameter configurations are represented as + * {@code XmlNode} values rather than instantiated as plugin objects. Values supplied through separate injection + * mechanisms such as {@code @Resolution} are not included. + * + * The returned values represent configured parameters and descriptor defaults, + * not necessarily the complete runtime state of an initialized Mojo. + * + * The current implementation accepts Maven's {@code DefaultProject} and + * {@code DefaultMojoExecution} implementations; other implementations are rejected. + * + * Parameter expressions are resolved using the supplied project's context and + * effective properties. + * + * The plugin realm's class loader is temporarily set as the thread context + * class loader while resolving parameters and is restored afterward. + * + * @param project the project associated with the Mojo execution + * @param mojoExecution the Mojo execution whose parameters are to be resolved + * @return a map of canonical parameter names to their resolved values; + * values are either type-converted Java values or {@code XmlNode} + * representations of plugin-specific configuration; + * parameters without configured or default values are omitted + */ + @Nonnull + Map getParameters(@Nonnull Project project, @Nonnull MojoExecution mojoExecution); +} diff --git a/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/DefaultMojoConfigurationService.java b/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/DefaultMojoConfigurationService.java new file mode 100644 index 000000000000..3f7503ffc2c3 --- /dev/null +++ b/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 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(); + } catch (PluginResolutionException | PluginContainerException e) { + throw new IllegalStateException("Could not resolve plugin realm", e); + } + } + + ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); + + try { + Thread.currentThread().setContextClassLoader(pluginRealm); + + Class mojoClass = Class.forName(mojoDescriptor.getImplementation(), false, pluginRealm); + + ExpressionEvaluator evaluator; + if (mojoDescriptor.isV4Api()) { + evaluator = new PluginParameterExpressionEvaluatorV4(session, project, mojoExecution); + } else { + evaluator = new PluginParameterExpressionEvaluator(interpolationSession, delegate); + } + + PlexusConfiguration configuration = new DefaultPlexusConfiguration("configuration"); + + if (mojoExecution.getConfiguration().isPresent()) { + configuration = XmlPlexusConfiguration.toPlexusConfiguration( + mojoExecution.getConfiguration().get()); + } + configuration = PluginConfigurationInterpolator.interpolateConfiguration( + configuration, evaluator, interpolationSession); + + EnhancedCompositeBeanHelper helper = + new EnhancedCompositeBeanHelper(new EnhancedConverterLookup(), pluginRealm, evaluator, null); + + Map parameters = new LinkedHashMap<>(); + Set configuredParameters = new HashSet<>(); + + for (int i = 0; i < configuration.getChildCount(); i++) { + PlexusConfiguration element = configuration.getChild(i); + String propertyName = toPropertyName(element.getName()); + + Parameter parameter = mojoExecution.getDescriptor().getParameters().stream() + .filter(p -> p.getName().equals(propertyName) + || (p.getAlias() != null + && toPropertyName(p.getAlias()).equals(propertyName))) + .findFirst() + .orElse(null); + + if (parameter == null) { + continue; + } + + configuredParameters.add(parameter.getName()); + + Object value = resolveParameterValue(helper, mojoClass, parameter.getName(), element); + + if (value != null) { + parameters.put(parameter.getName(), value); + } + } + + for (Parameter parameter : mojoExecution.getDescriptor().getParameters()) { + if (configuredParameters.contains(parameter.getName()) || parameter.getDefaultValue() == null) { + continue; + } + + PlexusConfiguration defaultConfiguration = new DefaultPlexusConfiguration(parameter.getName()); + defaultConfiguration.setAttribute("default-value", parameter.getDefaultValue()); + + Object value = resolveParameterValue(helper, mojoClass, parameter.getName(), defaultConfiguration); + + if (value != null) { + parameters.put(parameter.getName(), value); + } + } + + return parameters; + } catch (ComponentConfigurationException | ClassNotFoundException e) { + throw new IllegalStateException("Could not resolve Mojo parameters", e); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); + } + } + + private String toPropertyName(String name) { + StringBuilder result = new StringBuilder(); + boolean uppercaseNext = false; + + for (char c : name.toCharArray()) { + if (c == '-' || c == '_') { + uppercaseNext = true; + } else { + result.append(uppercaseNext ? Character.toUpperCase(c) : c); + uppercaseNext = false; + } + } + + return result.toString(); + } +} diff --git a/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedCompositeBeanHelper.java b/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/EnhancedCompositeBeanHelper.java new file mode 100644 index 000000000000..1472e35052ae --- /dev/null +++ b/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, Map> METHOD_CACHE = new ConcurrentHashMap<>(); + + // Cache for field lookups: Class -> FieldName -> Field + private static final ConcurrentMap, Map> 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 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 classMethodCache = METHOD_CACHE.computeIfAbsent(beanType, this::buildMethodCache); + + String title = Character.toTitleCase(propertyName.charAt(0)) + propertyName.substring(1); + + // Try setter first + MethodInfo setter = classMethodCache.get("set" + title); + if (setter != null && isMethodCompatible(setter.method, valueType)) { + return setter; + } + + // Try adder + MethodInfo adder = classMethodCache.get("add" + title); + if (adder != null && isMethodCompatible(adder.method, valueType)) { + return adder; + } + + // Return first found for backward compatibility + return setter != null ? setter : adder; + } + + /** + * Build method cache for a class. + */ + private Map buildMethodCache(Class beanType) { + Map methodMap = new HashMap<>(); + + for (Method method : beanType.getMethods()) { + if (!Modifier.isStatic(method.getModifiers()) && method.getParameterCount() == 1) { + Type[] paramTypes = method.getGenericParameterTypes(); + methodMap.putIfAbsent(method.getName(), new MethodInfo(method, paramTypes[0])); + } + } + + return methodMap; + } + + /** + * Check if method is compatible with value type. + */ + private boolean isMethodCompatible(Method method, Class valueType) { + if (valueType == null) { + return true; + } + return method.getParameterTypes()[0].isAssignableFrom(valueType); + } + + /** + * Find field using cache for improved performance. + */ + private Field findCachedField(Class beanType, String fieldName) { + Map classFieldCache = FIELD_CACHE.computeIfAbsent(beanType, this::buildFieldCache); + return classFieldCache.get(fieldName); + } + + /** + * Build field cache for a class. + */ + private Map buildFieldCache(Class beanType) { + Map fieldMap = new HashMap<>(); + + for (Object member : new DeclaredMembers(beanType, View.FIELDS)) { + Field field = (Field) member; + if (!Modifier.isStatic(field.getModifiers())) { + fieldMap.put(field.getName(), field); + } + } + + return fieldMap; + } + + /** + * Convert property value for method parameter. + */ + private Object convertPropertyForMethod( + Class beanType, MethodInfo methodInfo, Class valueType, PlexusConfiguration configuration) + throws ComponentConfigurationException { + + TypeLiteral paramType = TypeLiteral.get(methodInfo.parameterType); + return convertProperty(beanType, valueType, configuration, paramType); + } + + /** + * Convert property value for field. + */ + private Object convertPropertyForField( + Class beanType, Field field, Class valueType, PlexusConfiguration configuration) + throws ComponentConfigurationException { + + TypeLiteral fieldType = TypeLiteral.get(field.getGenericType()); + return convertProperty(beanType, valueType, configuration, fieldType); + } + + private Object convertProperty( + Class beanType, Class valueType, PlexusConfiguration configuration, TypeLiteral paramType) + throws ComponentConfigurationException { + Class rawPropertyType = paramType.getRawType(); + + if (valueType != null && rawPropertyType.isAssignableFrom(valueType)) { + rawPropertyType = valueType; // pick more specific type + } + + return convertProperty(beanType, rawPropertyType, paramType.getType(), configuration); + } + + /** + * Convert property using appropriate converter. + */ + private Object convertProperty( + Class beanType, Class rawPropertyType, Type genericPropertyType, PlexusConfiguration configuration) + throws ComponentConfigurationException { + + ConfigurationConverter converter = lookup.lookupConverterForType(rawPropertyType); + + if (!(genericPropertyType instanceof Class) && converter instanceof ParameterizedConfigurationConverter) { + Type[] propertyTypeArgs = TypeArguments.get(genericPropertyType); + return ((ParameterizedConfigurationConverter) converter) + .fromConfiguration( + lookup, + configuration, + rawPropertyType, + propertyTypeArgs, + beanType, + loader, + evaluator, + listener); + } + + return converter.fromConfiguration( + lookup, configuration, rawPropertyType, beanType, loader, evaluator, listener); + } + + /** + * Set field value with cached accessibility. + */ + private void setFieldValue(Object bean, Field field, Object value) throws IllegalAccessException { + if (!field.canAccess(bean)) { + field.setAccessible(true); + } + field.set(bean, value); + } + + /** + * Clear all caches. Useful for testing or memory management. + */ + public static void clearCaches() { + METHOD_CACHE.clear(); + FIELD_CACHE.clear(); + } +} diff --git a/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/MojoParameterType.java b/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/MojoParameterType.java new file mode 100644 index 000000000000..6663f86bd509 --- /dev/null +++ b/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/MojoParameterType.java @@ -0,0 +1,116 @@ +/* + * 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.io.File; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URI; +import java.net.URL; +import java.nio.file.Path; +import java.util.Collection; +import java.util.Map; +import java.util.UUID; + +/** + * Determines whether a Mojo parameter type can safely be returned + * without exposing plugin-specific classes. + */ +final class MojoParameterType { + + private MojoParameterType() {} + + static boolean isSafe(Type type) { + if (type instanceof Class clazz) { + return isSafeClass(clazz); + } + + if (type instanceof ParameterizedType parameterizedType) { + if (!(parameterizedType.getRawType() instanceof Class rawType)) { + return false; + } + + if (Collection.class.isAssignableFrom(rawType) || Map.class.isAssignableFrom(rawType)) { + if (rawType.getClassLoader() != null) { + return false; + } + } else if (!isSafeClass(rawType)) { + return false; + } + + for (Type argument : parameterizedType.getActualTypeArguments()) { + if (!isSafe(argument)) { + return false; + } + } + + return true; + } + + if (type instanceof GenericArrayType arrayType) { + return isSafe(arrayType.getGenericComponentType()); + } + + if (type instanceof WildcardType wildcardType) { + Type[] upperBounds = wildcardType.getUpperBounds(); + return upperBounds.length == 1 && isSafe(upperBounds[0]); + } + + return false; + } + + private static boolean isSafeClass(Class type) { + if (type.isPrimitive()) { + return true; + } + + if (type.isArray()) { + return isSafe(type.getComponentType()); + } + + if (type == String.class + || type == Boolean.class + || type == Character.class + || type == Byte.class + || type == Short.class + || type == Integer.class + || type == Long.class + || type == Float.class + || type == Double.class + || type == BigInteger.class + || type == BigDecimal.class + || type == File.class + || type == Path.class + || type == URI.class + || type == URL.class + || type == UUID.class) { + return true; + } + + if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) { + return false; + } + + return false; + } +} diff --git a/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/PluginConfigurationInterpolator.java b/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/PluginConfigurationInterpolator.java new file mode 100644 index 000000000000..a92e1c07c930 --- /dev/null +++ b/impl/maven-core/src/main/java/org/apache/maven/configuration/internal/PluginConfigurationInterpolator.java @@ -0,0 +1,172 @@ +/* + * 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.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.maven.api.xml.XmlNode; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.internal.xml.XmlPlexusConfiguration; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; +import org.codehaus.plexus.configuration.PlexusConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Applies the runtime expression interpolation used before Maven configures a Mojo. + */ +public final class PluginConfigurationInterpolator { + + private static final Logger LOGGER = LoggerFactory.getLogger(PluginConfigurationInterpolator.class); + + private static final Pattern EXPRESSION_PATTERN = Pattern.compile("\\$\\{([^}]+)}"); + + private PluginConfigurationInterpolator() {} + + /** + * Pre-interpolates expressions that were not available during model interpolation. + * + * @param configuration the plugin configuration + * @param evaluator the expression evaluator + * @param session the Maven session for determining model-time properties + * @return the interpolated configuration + */ + public static PlexusConfiguration interpolateConfiguration( + PlexusConfiguration configuration, ExpressionEvaluator evaluator, MavenSession session) { + if (!(configuration instanceof XmlPlexusConfiguration xmlConfig)) { + return configuration; + } + + Set modelTimePropertyNames = collectModelTimePropertyNames(session); + XmlNode original = xmlConfig.toXmlNode(); + XmlNode interpolated = interpolateXmlNode(original, evaluator, modelTimePropertyNames); + if (interpolated == original) { + return configuration; + } + return new XmlPlexusConfiguration(interpolated); + } + + private static Set collectModelTimePropertyNames(MavenSession session) { + Set names = new HashSet<>(); + Properties userProperties = session.getUserProperties(); + if (userProperties != null) { + names.addAll(userProperties.stringPropertyNames()); + } + Properties systemProperties = session.getSystemProperties(); + if (systemProperties != null) { + names.addAll(systemProperties.stringPropertyNames()); + } + org.apache.maven.project.MavenProject project = session.getCurrentProject(); + if (project != null && project.getOriginalModel() != null) { + Properties originalProperties = project.getOriginalModel().getProperties(); + if (originalProperties != null) { + names.addAll(originalProperties.stringPropertyNames()); + } + } + return names; + } + + private static boolean containsRuntimeExpression(String value, Set modelTimePropertyNames) { + Matcher matcher = EXPRESSION_PATTERN.matcher(value); + while (matcher.find()) { + if (!modelTimePropertyNames.contains(matcher.group(1))) { + return true; + } + } + return false; + } + + private static XmlNode interpolateXmlNode( + XmlNode node, ExpressionEvaluator evaluator, Set modelTimePropertyNames) { + boolean changed = false; + + String value = node.value(); + String newValue = value; + if (value != null && value.contains("${") && containsRuntimeExpression(value, modelTimePropertyNames)) { + try { + Object evaluated = evaluator.evaluate(value); + if (evaluated instanceof String evaluatedString && !evaluatedString.equals(value)) { + newValue = evaluatedString; + changed = true; + } + } catch (ExpressionEvaluationException e) { + LOGGER.debug("Failed to interpolate configuration value '{}': {}", value, e.getMessage()); + } + } + + Map attributes = node.attributes(); + Map newAttributes = attributes; + String defaultValue = attributes.get("default-value"); + if (defaultValue != null + && defaultValue.contains("${") + && containsRuntimeExpression(defaultValue, modelTimePropertyNames)) { + try { + Object evaluated = evaluator.evaluate(defaultValue); + if (evaluated instanceof String evaluatedString && !evaluatedString.equals(defaultValue)) { + newAttributes = new HashMap<>(attributes); + newAttributes.put("default-value", evaluatedString); + changed = true; + } + } catch (ExpressionEvaluationException e) { + LOGGER.debug( + "Failed to interpolate configuration default-value '{}': {}", defaultValue, e.getMessage()); + } + } + + List children = node.children(); + List newChildren = children; + for (int i = 0; i < children.size(); i++) { + XmlNode child = children.get(i); + XmlNode newChild = interpolateXmlNode(child, evaluator, modelTimePropertyNames); + if (newChild != child && newChildren == children) { + newChildren = new ArrayList<>(children.size()); + for (int j = 0; j < i; j++) { + newChildren.add(children.get(j)); + } + changed = true; + } + if (newChildren != children) { + newChildren.add(newChild); + } + } + + if (!changed) { + return node; + } + + return XmlNode.newBuilder() + .name(node.name()) + .value(newValue) + .attributes(newAttributes) + .children(newChildren) + .namespaceUri(node.namespaceUri()) + .prefix(node.prefix()) + .inputLocation(node.inputLocation()) + .build(); + } +} diff --git a/impl/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java b/impl/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java index e637ea4a1085..5f3d03db5a17 100644 --- a/impl/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java +++ b/impl/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java @@ -34,16 +34,11 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Properties; -import java.util.Set; import java.util.function.Supplier; import java.util.jar.JarFile; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.ZipEntry; @@ -64,6 +59,7 @@ import org.apache.maven.api.xml.XmlNode; import org.apache.maven.artifact.Artifact; import org.apache.maven.classrealm.ClassRealmManager; +import org.apache.maven.configuration.internal.PluginConfigurationInterpolator; import org.apache.maven.di.Injector; import org.apache.maven.di.Key; import org.apache.maven.di.impl.BindingStyler; @@ -947,9 +943,6 @@ private void populateMojoExecutionFields( } } - /** Pattern to extract property names from {@code ${propName}} expressions. */ - private static final Pattern EXPRESSION_PATTERN = Pattern.compile("\\$\\{([^}]+)}"); - /** * Pre-interpolates a plugin configuration tree by resolving {@code ${...}} property references * that were set dynamically at runtime (not available during model interpolation). Returns a new @@ -973,139 +966,7 @@ private void populateMojoExecutionFields( */ private PlexusConfiguration interpolateConfiguration( PlexusConfiguration configuration, ExpressionEvaluator evaluator, MavenSession session) { - if (!(configuration instanceof XmlPlexusConfiguration xmlConfig)) { - return configuration; - } - - Set modelTimePropertyNames = collectModelTimePropertyNames(session); - - XmlNode original = xmlConfig.toXmlNode(); - XmlNode interpolated = interpolateXmlNode(original, evaluator, modelTimePropertyNames); - if (interpolated == original) { - return configuration; - } - return new XmlPlexusConfiguration(interpolated); - } - - /** - * Collects the set of property names that were available during model interpolation. - * Properties in this set should NOT be re-interpolated, because any surviving {@code ${...}} - * reference to them was intentionally escaped. - */ - private Set collectModelTimePropertyNames(MavenSession session) { - Set names = new HashSet<>(); - // User properties (from -D on CLI) - Properties userProps = session.getUserProperties(); - if (userProps != null) { - names.addAll(userProps.stringPropertyNames()); - } - // System properties - Properties sysProps = session.getSystemProperties(); - if (sysProps != null) { - names.addAll(sysProps.stringPropertyNames()); - } - // POM properties from the original model (before runtime additions) - MavenProject project = session.getCurrentProject(); - if (project != null && project.getOriginalModel() != null) { - Properties origProps = project.getOriginalModel().getProperties(); - if (origProps != null) { - names.addAll(origProps.stringPropertyNames()); - } - } - return names; - } - - /** - * Checks whether a string value contains any {@code ${propName}} expression where - * {@code propName} is NOT in the model-time property set. Only such expressions need - * pre-interpolation (they were set at runtime and model interpolation couldn't see them). - */ - private boolean containsRuntimeExpression(String value, Set modelTimePropertyNames) { - Matcher matcher = EXPRESSION_PATTERN.matcher(value); - while (matcher.find()) { - String propName = matcher.group(1); - if (!modelTimePropertyNames.contains(propName)) { - return true; - } - } - return false; - } - - /** - * Recursively interpolates an {@link XmlNode} tree, resolving only {@code ${...}} expressions - * that reference runtime properties (not available at model interpolation time). Returns the - * original node if no interpolation was needed, or a new node with resolved values otherwise. - */ - private XmlNode interpolateXmlNode( - XmlNode node, ExpressionEvaluator evaluator, Set modelTimePropertyNames) { - boolean changed = false; - - // Interpolate the text value (only if it contains runtime expressions) - String value = node.value(); - String newValue = value; - if (value != null && value.contains("${") && containsRuntimeExpression(value, modelTimePropertyNames)) { - try { - Object evaluated = evaluator.evaluate(value); - if (evaluated instanceof String evaluatedStr && !evaluatedStr.equals(value)) { - newValue = evaluatedStr; - changed = true; - } - } catch (ExpressionEvaluationException e) { - logger.debug("Failed to interpolate configuration value '{}': {}", value, e.getMessage()); - } - } - - // Interpolate the default-value attribute if present (only if it contains runtime expressions) - Map attributes = node.attributes(); - Map newAttributes = attributes; - String defaultValue = attributes.get("default-value"); - if (defaultValue != null - && defaultValue.contains("${") - && containsRuntimeExpression(defaultValue, modelTimePropertyNames)) { - try { - Object evaluated = evaluator.evaluate(defaultValue); - if (evaluated instanceof String evaluatedStr && !evaluatedStr.equals(defaultValue)) { - newAttributes = new HashMap<>(attributes); - newAttributes.put("default-value", evaluatedStr); - changed = true; - } - } catch (ExpressionEvaluationException e) { - logger.debug( - "Failed to interpolate configuration default-value '{}': {}", defaultValue, e.getMessage()); - } - } - - // Recurse into children - List children = node.children(); - List newChildren = children; - for (int i = 0; i < children.size(); i++) { - XmlNode child = children.get(i); - XmlNode newChild = interpolateXmlNode(child, evaluator, modelTimePropertyNames); - if (newChild != child && newChildren == children) { - newChildren = new ArrayList<>(children.size()); - for (int j = 0; j < i; j++) { - newChildren.add(children.get(j)); - } - changed = true; - } - if (newChildren != children) { - newChildren.add(newChild); - } - } - - if (!changed) { - return node; - } - - return XmlNode.newBuilder() - .name(node.name()) - .value(newValue) - .attributes(newAttributes) - .children(newChildren) - .namespaceUri(node.namespaceUri()) - .prefix(node.prefix()) - .inputLocation(node.inputLocation()) - .build(); + return PluginConfigurationInterpolator.interpolateConfiguration(configuration, evaluator, session); } private void validateParameters( diff --git a/impl/maven-core/src/test/java/org/apache/maven/configuration/internal/DefaultMojoConfigurationServiceTest.java b/impl/maven-core/src/test/java/org/apache/maven/configuration/internal/DefaultMojoConfigurationServiceTest.java new file mode 100644 index 000000000000..c7a2ddb21e23 --- /dev/null +++ b/impl/maven-core/src/test/java/org/apache/maven/configuration/internal/DefaultMojoConfigurationServiceTest.java @@ -0,0 +1,913 @@ +/* + * 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 java.io.File; +import java.net.URI; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import org.apache.maven.AbstractCoreMavenComponentTestCase; +import org.apache.maven.api.MojoExecution; +import org.apache.maven.api.Project; +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.DefaultLookup; +import org.apache.maven.internal.impl.DefaultMojoExecution; +import org.apache.maven.internal.impl.DefaultProject; +import org.apache.maven.internal.impl.DefaultSession; +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.PluginParameterExpressionEvaluatorV4; +import org.apache.maven.plugin.descriptor.PluginDescriptor; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.classworlds.ClassWorld; +import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; +import org.codehaus.plexus.configuration.PlexusConfiguration; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.eclipse.aether.RepositorySystem; +import org.junit.jupiter.api.BeforeEach; +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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +class DefaultMojoConfigurationServiceTest extends AbstractCoreMavenComponentTestCase { + + @Inject + PlexusContainer container; + + org.apache.maven.execution.MavenSession mavenSession; + + DefaultSession session; + + @BeforeEach + void setUp() throws Exception { + mavenSession = createMavenSession(null); + session = new DefaultSession( + mavenSession, mock(RepositorySystem.class), null, null, new DefaultLookup(container), null); + } + + @Test + void readsConfiguredParameterWithoutInstantiatingMojo() throws Exception { + TestMojo.setterCalls = 0; + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("message") + .alias("display-message") + .type(String.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-plugin-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom message = new Xpp3Dom("display-message"); + message.setValue("Hello Maven"); + configuration.addChild(message); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + MojoConfigurationService service = session.getService(MojoConfigurationService.class); + assertNotNull(service); + + Map parameters = service.getParameters(project, execution); + + assertEquals("Hello Maven", parameters.get("message")); + assertEquals(0, TestMojo.setterCalls, "Mojo setter must not be invoked"); + } + + @Test + void resolvesParametersUsingLegacyV3ExpressionEvaluator() throws Exception { + TestMojo.setterCalls = 0; + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-v3-plugin-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(); + legacyDescriptor.setPluginDescriptor(pluginDescriptor); + legacyDescriptor.setGoal("test"); + legacyDescriptor.setImplementation(TestMojo.class.getName()); + + org.apache.maven.plugin.descriptor.Parameter legacyParameter = + new org.apache.maven.plugin.descriptor.Parameter(); + legacyParameter.setName("message"); + legacyParameter.setType(String.class.getName()); + legacyDescriptor.addParameter(legacyParameter); + + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom message = new Xpp3Dom("message"); + message.setValue("${project.artifactId}"); + configuration.addChild(message); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + MojoConfigurationService service = session.getService(MojoConfigurationService.class); + assertNotNull(service); + + Map parameters = service.getParameters(project, execution); + + assertFalse(legacyDescriptor.isV4Api()); + assertEquals(mavenProject.getArtifactId(), parameters.get("message")); + assertEquals(0, TestMojo.setterCalls, "Mojo setter must not be invoked"); + } + + @Test + void resolvesProjectBasedirExpression() throws Exception { + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("outputDirectory") + .type(Path.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-expression-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom outputDirectory = new Xpp3Dom("outputDirectory"); + outputDirectory.setValue("${project.basedir}"); + configuration.addChild(outputDirectory); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + assertEquals(project.getBasedir(), parameters.get("outputDirectory")); + } + + @Test + void convertsConfiguredIntegerParameter() throws Exception { + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("count") + .type(Integer.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-integer-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom count = new Xpp3Dom("count"); + count.setValue("42"); + configuration.addChild(count); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + assertEquals(42, parameters.get("count")); + assertInstanceOf(Integer.class, parameters.get("count")); + } + + @Test + void convertsConfiguredBooleanParameter() throws Exception { + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("enabled") + .type(Boolean.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-boolean-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom enabled = new Xpp3Dom("enabled"); + enabled.setValue("true"); + configuration.addChild(enabled); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + assertEquals(true, parameters.get("enabled")); + assertInstanceOf(Boolean.class, parameters.get("enabled")); + } + + @Test + void resolvesRuntimeProjectPropertyExpression() throws Exception { + TestMojo.setterCalls = 0; + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + + mavenProject.getProperties().setProperty("runtime.customValue", "runtime-value"); + + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("message") + .type(String.class.getName()) + .build(); + + Parameter escaped = Parameter.newBuilder() + .name("setterOnly") + .type(String.class.getName()) + .build(); + + Parameter unresolved = Parameter.newBuilder() + .name("defaultMessage") + .type(String.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter, escaped, unresolved)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = + world.newRealm("test-runtime-property-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + configuration.addChild(new Xpp3Dom("message")); + configuration.getChild("message").setValue("${runtime.customValue}"); + configuration.addChild(new Xpp3Dom("setterOnly")); + configuration.getChild("setterOnly").setValue("$${runtime.customValue}"); + configuration.addChild(new Xpp3Dom("defaultMessage")); + configuration.getChild("defaultMessage").setValue("${runtime.unresolved}"); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + assertEquals("runtime-value", parameters.get("message")); + assertEquals("runtime-value", parameters.get("setterOnly")); + assertFalse(parameters.containsKey("defaultMessage")); + assertEquals(0, TestMojo.setterCalls, "Mojo setter must not be invoked"); + } + + @Test + void resolvesRuntimeProjectPropertyInUriLikeMavenConfiguration() throws Exception { + TestMojo.setterCalls = 0; + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + mavenProject.getProperties().setProperty("runtime.uri", "https://example.invalid/runtime-path"); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = + Parameter.newBuilder().name("uri").type(URI.class.getName()).build(); + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-runtime-uri-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom uri = new Xpp3Dom("uri"); + uri.setValue("${runtime.uri}"); + configuration.addChild(uri); + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + Map parameters = service.getParameters(project, execution); + + ExpressionEvaluator evaluator = new PluginParameterExpressionEvaluatorV4(session, project, execution); + org.apache.maven.execution.MavenSession interpolationSession = mavenSession.clone(); + interpolationSession.setCurrentProject(mavenProject); + PlexusConfiguration normalConfiguration = XmlPlexusConfiguration.toPlexusConfiguration( + execution.getConfiguration().orElseThrow()); + normalConfiguration = PluginConfigurationInterpolator.interpolateConfiguration( + normalConfiguration, evaluator, interpolationSession); + TestUriBean bean = new TestUriBean(); + new EnhancedComponentConfigurator().configureComponent(bean, normalConfiguration, evaluator, realm, null); + + assertEquals(URI.create("https://example.invalid/runtime-path"), parameters.get("uri")); + assertEquals(bean.getUri(), parameters.get("uri")); + assertEquals(0, TestMojo.setterCalls, "Mojo setter must not be invoked"); + } + + @Test + void readsSetterOnlyParameterWithoutInvokingSetter() throws Exception { + TestMojo.setterCalls = 0; + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("setterOnly") + .type(String.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-setter-only-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom setterOnly = new Xpp3Dom("setterOnly"); + setterOnly.setValue("setter-only-value"); + configuration.addChild(setterOnly); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + assertEquals("setter-only-value", parameters.get("setterOnly")); + assertEquals(0, TestMojo.setterCalls, "Mojo setter must not be invoked"); + } + + @Test + void resolvesDefaultParameterValue() throws Exception { + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("defaultMessage") + .type(String.class.getName()) + .defaultValue("default-value") + .build(); + + Parameter retries = Parameter.newBuilder() + .name("retries") + .type(Integer.class.getName()) + .defaultValue("5") + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter, retries)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-default-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, new Xpp3Dom("configuration")); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + assertEquals("default-value", parameters.get("defaultMessage")); + assertEquals(5, parameters.get("retries")); + assertInstanceOf(Integer.class, parameters.get("retries")); + } + + @Test + void returnsXmlForPluginSpecificDefaultParameter() throws Exception { + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("customOptions") + .type(TestOptions.class.getName()) + .defaultValue("custom-default") + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = + world.newRealm("test-custom-default-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, new Xpp3Dom("configuration")); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + XmlNode resolvedValue = (XmlNode) parameters.get("customOptions"); + + assertNotNull(resolvedValue); + assertEquals("customOptions", resolvedValue.name()); + assertEquals("custom-default", resolvedValue.value()); + } + + @Test + void convertsConfiguredStringListParameter() throws Exception { + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("compilerArgs") + .type(List.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-list-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom compilerArgs = new Xpp3Dom("compilerArgs"); + compilerArgs.addChild(new Xpp3Dom("arg")); + compilerArgs.getChild(0).setValue("-Xlint"); + Xpp3Dom secondArg = new Xpp3Dom("arg"); + secondArg.setValue("-parameters"); + compilerArgs.addChild(secondArg); + configuration.addChild(compilerArgs); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + assertEquals(List.of("-Xlint", "-parameters"), parameters.get("compilerArgs")); + } + + @Test + void returnsNestedPluginSpecificConfigurationAsXmlWithoutInvokingSetters() throws Exception { + TestOptions.setterCalls = 0; + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + // Create nested configuration + Xpp3Dom configuration = new Xpp3Dom("configuration"); + + Xpp3Dom optionsConfig = new Xpp3Dom("options"); + + Xpp3Dom compiler = new Xpp3Dom("compiler"); + compiler.setValue("javac"); + optionsConfig.addChild(compiler); + + Xpp3Dom source = new Xpp3Dom("source"); + source.setValue("17"); + optionsConfig.addChild(source); + + configuration.addChild(optionsConfig); + + // Define the Mojo parameter + Parameter parameter = Parameter.newBuilder() + .name("options") + .type(TestOptions.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + // Create plugin descriptor and realm + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + ClassWorld world = new ClassWorld(); + ClassRealm realm = world.newRealm("test-nested-realm", getClass().getClassLoader()); + pluginDescriptor.setClassRealm(realm); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + // Create Mojo execution + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, configuration); + + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + // Resolve parameters + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), mock(MavenPluginManager.class)); + + Map parameters = service.getParameters(project, execution); + + // Verify nested XML configuration + XmlNode resolvedOptions = (XmlNode) parameters.get("options"); + + assertNotNull(resolvedOptions); + assertEquals("options", resolvedOptions.name()); + assertEquals("javac", resolvedOptions.child("compiler").value()); + assertEquals("17", resolvedOptions.child("source").value()); + assertEquals(0, TestOptions.setterCalls, "Nested parameter setters must not run"); + } + + @Test + void createsPluginRealmUsingSuppliedProjectContext() throws Exception { + + org.apache.maven.project.MavenProject mavenProject = + mavenSession.getProjects().get(0); + org.apache.maven.project.MavenProject originalCurrentProject = mavenSession.getCurrentProject(); + + mavenProject.setFile(new File(System.getProperty("user.dir"), "pom.xml")); + Project project = new DefaultProject(InternalMavenSession.from(session), mavenProject); + + Parameter parameter = Parameter.newBuilder() + .name("message") + .type(String.class.getName()) + .build(); + + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .parameters(List.of(parameter)) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + pluginDescriptor.addComponentDescriptor(legacyDescriptor); + + org.apache.maven.plugin.MojoExecution delegate = + new org.apache.maven.plugin.MojoExecution(legacyDescriptor, new Xpp3Dom("configuration")); + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + ClassRealm realm = new ClassRealm(new ClassWorld(), "test", getClass().getClassLoader()); + MavenPluginManager pluginManager = mock(MavenPluginManager.class); + + doAnswer(invocation -> { + org.apache.maven.execution.MavenSession realmSession = invocation.getArgument(1); + assertEquals(mavenProject, realmSession.getCurrentProject()); + pluginDescriptor.setClassRealm(realm); + return null; + }) + .when(pluginManager) + .setupPluginRealm(eq(pluginDescriptor), any(), isNull(), isNull(), isNull()); + + DefaultMojoConfigurationService service = + new DefaultMojoConfigurationService(InternalMavenSession.from(session), pluginManager); + + service.getParameters(project, execution); + + assertEquals(originalCurrentProject, mavenSession.getCurrentProject()); + verify(pluginManager).setupPluginRealm(eq(pluginDescriptor), any(), isNull(), isNull(), isNull()); + } + + @Test + void rejectsUnsupportedMojoExecutionImplementation() { + MojoExecution mojoExecution = mock(MojoExecution.class); + Project project = mock(Project.class); + + IllegalArgumentException exception = assertThrows( + IllegalArgumentException.class, + () -> new DefaultMojoConfigurationService(session, mock(MavenPluginManager.class)) + .getParameters(project, mojoExecution)); + + assertTrue(exception.getMessage().contains(mojoExecution.getClass().getName())); + } + + @Test + void rejectsUnsupportedProjectImplementation() throws Exception { + org.apache.maven.api.plugin.descriptor.MojoDescriptor apiDescriptor = + org.apache.maven.api.plugin.descriptor.MojoDescriptor.newBuilder() + .goal("test") + .implementation(TestMojo.class.getName()) + .build(); + + PluginDescriptor pluginDescriptor = new PluginDescriptor(); + pluginDescriptor.setGroupId("org.apache.maven.test"); + pluginDescriptor.setArtifactId("test-plugin"); + pluginDescriptor.setVersion("1"); + + org.apache.maven.plugin.descriptor.MojoDescriptor legacyDescriptor = + new org.apache.maven.plugin.descriptor.MojoDescriptor(pluginDescriptor, apiDescriptor); + + org.apache.maven.plugin.MojoExecution delegate = new org.apache.maven.plugin.MojoExecution(legacyDescriptor); + + MojoExecution execution = new DefaultMojoExecution(InternalMavenSession.from(session), delegate); + + Project unsupportedProject = mock(Project.class); + + IllegalArgumentException exception = assertThrows( + IllegalArgumentException.class, + () -> new DefaultMojoConfigurationService( + InternalMavenSession.from(session), mock(MavenPluginManager.class)) + .getParameters(unsupportedProject, execution)); + + assertTrue(exception.getMessage().contains(unsupportedProject.getClass().getName())); + } + + @Override + protected String getProjectsDirectory() { + return ""; + } + + public static class TestOptions { + static int setterCalls; + + private String compiler; + private String source; + + public void setCompiler(String compiler) { + setterCalls++; + this.compiler = compiler; + } + + public void setSource(String source) { + setterCalls++; + this.source = source; + } + } + + public static class TestUriBean { + private URI uri; + + public URI getUri() { + return uri; + } + + public void setUri(URI uri) { + this.uri = uri; + } + } + + static class TestMojo { + static int setterCalls; + + private Path outputDirectory; + private URI uri; + private Integer count; + private Boolean enabled; + private Integer retries; + private String setterOnly; + private String defaultMessage; + private TestOptions options; + private List compilerArgs; + private TestOptions customOptions; + + TestMojo() { + throw new AssertionError("Mojo must not be instantiated"); + } + + public void setMessage(String message) { + setterCalls++; + } + + public void setSetterOnly(String setterOnly) { + setterCalls++; + } + } +} diff --git a/impl/maven-core/src/test/java/org/apache/maven/configuration/internal/MojoParameterTypeTest.java b/impl/maven-core/src/test/java/org/apache/maven/configuration/internal/MojoParameterTypeTest.java new file mode 100644 index 000000000000..7988ba1ef851 --- /dev/null +++ b/impl/maven-core/src/test/java/org/apache/maven/configuration/internal/MojoParameterTypeTest.java @@ -0,0 +1,92 @@ +/* + * 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.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Type; +import java.net.URI; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MojoParameterTypeTest { + + @Test + void acceptsSafeJdkTypes() { + assertSafe(String.class); + assertSafe(Integer.class); + assertSafe(boolean.class); + assertSafe(File.class); + assertSafe(Path.class); + assertSafe(URI.class); + } + + @Test + void acceptsSafeParameterizedCollections() throws Exception { + assertSafe(fieldType("arrayList")); + assertSafe(fieldType("hashMap")); + assertSafe(fieldType("strings")); + assertSafe(fieldType("values")); + } + + @Test + void rejectsUnsafeTypes() throws Exception { + assertUnsafe(PluginValue.class); + assertUnsafe(fieldType("pluginList")); + assertUnsafe(fieldType("rawList")); + assertUnsafe(fieldType("unknownValues")); + assertUnsafe(fieldType("pluginValues")); + } + + private static void assertSafe(Type type) { + assertTrue(MojoParameterType.isSafe(type), () -> "Expected safe type: " + type); + } + + private static void assertUnsafe(Type type) { + assertFalse(MojoParameterType.isSafe(type), () -> "Expected unsafe type: " + type); + } + + private static Type fieldType(String name) throws Exception { + Field field = TypeSamples.class.getDeclaredField(name); + return field.getGenericType(); + } + + private static class PluginList extends ArrayList {} + + private static class PluginValue {} + + private static class TypeSamples { + PluginList pluginList; + ArrayList arrayList; + HashMap hashMap; + List strings; + Map values; + List rawList; + List unknownValues; + List pluginValues; + } +}