diff --git a/.github/workflows/maven-verify.yml b/.github/workflows/maven-verify.yml index fa7dc4b..9177951 100644 --- a/.github/workflows/maven-verify.yml +++ b/.github/workflows/maven-verify.yml @@ -26,4 +26,4 @@ jobs: name: Verify uses: apache/maven-gh-actions-shared/.github/workflows/maven-verify.yml@v4 with: - jdk-matrix: '[ "8", "11", "17" ]' + jdk-matrix: '[ "17", "21" ]' diff --git a/maven-plugin-testing-harness/pom.xml b/maven-plugin-testing-harness/pom.xml index beaa39d..420508c 100644 --- a/maven-plugin-testing-harness/pom.xml +++ b/maven-plugin-testing-harness/pom.xml @@ -35,7 +35,7 @@ under the License. org.junit junit-bom - 5.10.0 + 5.10.1 pom import @@ -64,9 +64,8 @@ under the License. org.apache.maven - maven-plugin-api + maven-xml-impl ${mavenVersion} - provided org.apache.maven @@ -74,6 +73,10 @@ under the License. ${mavenVersion} provided + + org.eclipse.sisu + org.eclipse.sisu.plexus + @@ -85,39 +88,10 @@ under the License. org.codehaus.plexus plexus-xml - 4.0.0 + 4.0.3 true - - org.codehaus.plexus - plexus-archiver - 4.8.0 - - - org.codehaus.plexus - plexus-testing - 1.1.0 - - - - org.junit.jupiter - junit-jupiter-api - - - - - - com.google.guava - guava - 32.0.1-jre - - - junit - junit - 4.13.2 - true - org.junit.jupiter junit-jupiter-api @@ -130,8 +104,14 @@ under the License. org.slf4j - slf4j-simple - 1.7.36 + slf4j-api + 2.0.13 + + + + com.google.inject + guice + 6.0.0 test diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/di/testing/MavenDIExtension.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/di/testing/MavenDIExtension.java new file mode 100644 index 0000000..c6f3b86 --- /dev/null +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/di/testing/MavenDIExtension.java @@ -0,0 +1,150 @@ +/* + * 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.di.testing; + +import java.io.*; + +import org.apache.maven.di.Injector; +import org.apache.maven.di.Key; +import org.apache.maven.di.impl.DIException; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +/** + * This is a slightly modified version of the original plexus class + * available at https://raw.githubusercontent.com/codehaus-plexus/plexus-containers/master/plexus-container-default/ + * src/main/java/org/codehaus/plexus/PlexusTestCase.java + * in order to migrate the tests to JUnit 4. + * + * @author Jason van Zyl + * @author Trygve Laugstøl + * @author Michal Maczka + * @author Guillaume Nodet + */ +public class MavenDIExtension implements BeforeEachCallback, AfterEachCallback { + protected static ExtensionContext context; + protected Injector injector; + protected static String basedir; + + @Override + public void beforeEach(ExtensionContext context) throws Exception { + basedir = getBasedir(); + + setContext(context); + + getInjector().bindInstance((Class) context.getRequiredTestClass(), context.getRequiredTestInstance()); + getInjector().injectInstance(context.getRequiredTestInstance()); + } + + protected void setContext(ExtensionContext context) { + this.context = context; + } + + @SuppressWarnings("unchecked") + protected void setupContainer() { + try { + injector = Injector.create(); + injector.bindInstance(ExtensionContext.class, this.context); + injector.discover(this.context.getRequiredTestClass().getClassLoader()); + injector.bindInstance(Injector.class, injector); + injector.bindInstance((Class) this.context.getRequiredTestClass(), this.context.getRequiredTestInstance()); + } catch (Exception e) { + throw new IllegalArgumentException("Failed to create DI injector.", e); + } + } + + @Override + public void afterEach(ExtensionContext context) throws Exception { + if (injector != null) { + // TODO: implement + // injector.dispose(); + injector = null; + } + } + + public Injector getInjector() { + if (injector == null) { + setupContainer(); + } + + return injector; + } + + // ---------------------------------------------------------------------- + // Container access + // ---------------------------------------------------------------------- + + protected T lookup(Class componentClass) throws DIException { + return getInjector().getInstance(componentClass); + } + + protected T lookup(Class componentClass, String roleHint) throws DIException { + return getInjector().getInstance(Key.ofType(componentClass, roleHint)); + } + + protected T lookup(Class componentClass, Object qualifier) throws DIException { + return getInjector().getInstance(Key.ofType(componentClass, qualifier)); + } + + protected void release(Object component) throws DIException { + // TODO: implement + // getInjector().release(component); + } + + // ---------------------------------------------------------------------- + // Helper methods for sub classes + // ---------------------------------------------------------------------- + + public static File getTestFile(String path) { + return new File(getBasedir(), path); + } + + public static File getTestFile(String basedir, String path) { + File basedirFile = new File(basedir); + + if (!basedirFile.isAbsolute()) { + basedirFile = getTestFile(basedir); + } + + return new File(basedirFile, path); + } + + public static String getTestPath(String path) { + return getTestFile(path).getAbsolutePath(); + } + + public static String getTestPath(String basedir, String path) { + return getTestFile(basedir, path).getAbsolutePath(); + } + + public static String getBasedir() { + if (basedir != null) { + return basedir; + } + + basedir = System.getProperty("basedir"); + + if (basedir == null) { + basedir = new File("").getAbsolutePath(); + } + + return basedir; + } +} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoTest.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/di/testing/MavenDITest.java similarity index 89% rename from maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoTest.java rename to maven-plugin-testing-harness/src/main/java/org/apache/maven/api/di/testing/MavenDITest.java index 09461bd..ddc6d2f 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoTest.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/di/testing/MavenDITest.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugin.testing.junit5; +package org.apache.maven.api.di.testing; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -26,9 +26,9 @@ import org.junit.jupiter.api.extension.ExtendWith; /** - * + * Plexus test */ @Retention(RetentionPolicy.RUNTIME) -@ExtendWith(MojoExtension.class) +@ExtendWith(MavenDIExtension.class) @Target(ElementType.TYPE) -public @interface MojoTest {} +public @interface MavenDITest {} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoParameters.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/Basedir.java similarity index 86% rename from maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoParameters.java rename to maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/Basedir.java index 33c0a23..69eaba2 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoParameters.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/Basedir.java @@ -16,8 +16,9 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugin.testing.junit5; +package org.apache.maven.api.plugin.testing; +import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -25,6 +26,7 @@ * Mojo parameters container */ @Retention(RetentionPolicy.RUNTIME) -public @interface MojoParameters { - MojoParameter[] value(); +@Inherited +public @interface Basedir { + String value() default ""; } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/InjectMojo.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/InjectMojo.java index e094d06..272eb9b 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/InjectMojo.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/InjectMojo.java @@ -18,6 +18,7 @@ */ package org.apache.maven.api.plugin.testing; +import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -25,11 +26,10 @@ * */ @Retention(RetentionPolicy.RUNTIME) +@Inherited public @interface InjectMojo { String goal(); - String pom(); - - boolean empty() default false; + String pom() default ""; } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoExtension.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoExtension.java index b217fab..b855dde 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoExtension.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoExtension.java @@ -18,68 +18,75 @@ */ package org.apache.maven.api.plugin.testing; -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; +import java.io.*; import java.lang.reflect.AccessibleObject; +import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.net.URL; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; -import com.google.inject.internal.ProviderMethodsModule; import org.apache.maven.api.MojoExecution; import org.apache.maven.api.Project; import org.apache.maven.api.Session; +import org.apache.maven.api.di.Named; +import org.apache.maven.api.di.Priority; +import org.apache.maven.api.di.Provides; +import org.apache.maven.api.di.Singleton; +import org.apache.maven.api.di.testing.MavenDIExtension; +import org.apache.maven.api.model.Build; +import org.apache.maven.api.model.ConfigurationContainer; +import org.apache.maven.api.model.Model; import org.apache.maven.api.plugin.Log; import org.apache.maven.api.plugin.Mojo; +import org.apache.maven.api.plugin.descriptor.MojoDescriptor; +import org.apache.maven.api.plugin.descriptor.Parameter; +import org.apache.maven.api.plugin.descriptor.PluginDescriptor; +import org.apache.maven.api.plugin.testing.stubs.*; +import org.apache.maven.api.services.ArtifactDeployer; +import org.apache.maven.api.services.ArtifactFactory; +import org.apache.maven.api.services.ArtifactInstaller; +import org.apache.maven.api.services.ArtifactManager; +import org.apache.maven.api.services.LocalRepositoryManager; +import org.apache.maven.api.services.ProjectBuilder; +import org.apache.maven.api.services.ProjectManager; +import org.apache.maven.api.services.RepositoryFactory; +import org.apache.maven.api.services.VersionParser; +import org.apache.maven.api.services.xml.ModelXmlFactory; import org.apache.maven.api.xml.XmlNode; import org.apache.maven.configuration.internal.EnhancedComponentConfigurator; +import org.apache.maven.di.Injector; +import org.apache.maven.di.Key; +import org.apache.maven.di.impl.DIException; import org.apache.maven.internal.impl.DefaultLog; +import org.apache.maven.internal.impl.InternalSession; +import org.apache.maven.internal.impl.model.DefaultModelPathTranslator; +import org.apache.maven.internal.impl.model.DefaultPathTranslator; import org.apache.maven.internal.xml.XmlNodeImpl; +import org.apache.maven.internal.xml.XmlPlexusConfiguration; import org.apache.maven.lifecycle.internal.MojoDescriptorCreator; +import org.apache.maven.model.v4.MavenMerger; +import org.apache.maven.model.v4.MavenStaxReader; import org.apache.maven.plugin.PluginParameterExpressionEvaluatorV4; -import org.apache.maven.plugin.descriptor.MojoDescriptor; -import org.apache.maven.plugin.descriptor.Parameter; -import org.apache.maven.plugin.descriptor.PluginDescriptor; -import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; -import org.codehaus.plexus.DefaultPlexusContainer; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.component.configurator.ComponentConfigurator; +import org.apache.maven.plugin.descriptor.io.PluginDescriptorStaxReader; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; -import org.codehaus.plexus.testing.PlexusExtension; -import org.codehaus.plexus.util.InterpolationFilterReader; -import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.ReflectionUtils; import org.codehaus.plexus.util.xml.XmlStreamReader; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.ParameterContext; -import org.junit.jupiter.api.extension.ParameterResolutionException; -import org.junit.jupiter.api.extension.ParameterResolver; +import org.eclipse.aether.RepositorySystem; +import org.junit.jupiter.api.extension.*; +import org.junit.platform.commons.support.AnnotationSupport; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** * JUnit extension to help testing Mojos. The extension should be automatically registered * by adding the {@link MojoTest} annotation on the test class. @@ -87,8 +94,25 @@ * @see MojoTest * @see InjectMojo * @see MojoParameter + * @see Basedir */ -public class MojoExtension extends PlexusExtension implements ParameterResolver { +public class MojoExtension extends MavenDIExtension implements ParameterResolver, BeforeEachCallback { + + protected static String pluginBasedir; + protected static String basedir; + + public static String getTestId() { + return context.getRequiredTestClass().getSimpleName() + "-" + + context.getRequiredTestMethod().getName(); + } + + public static String getBasedir() { + return requireNonNull(basedir != null ? basedir : MavenDIExtension.basedir); + } + + public static String getPluginBasedir() { + return requireNonNull(pluginBasedir); + } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) @@ -101,115 +125,382 @@ public boolean supportsParameter(ParameterContext parameterContext, ExtensionCon public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { try { - InjectMojo injectMojo = parameterContext - .findAnnotation(InjectMojo.class) - .orElseGet(() -> parameterContext.getDeclaringExecutable().getAnnotation(InjectMojo.class)); - - Set mojoParameters = - new HashSet<>(parameterContext.findRepeatableAnnotations(MojoParameter.class)); - - Optional.ofNullable(parameterContext.getDeclaringExecutable().getAnnotation(MojoParameter.class)) - .ifPresent(mojoParameters::add); - - Optional.ofNullable(parameterContext.getDeclaringExecutable().getAnnotation(MojoParameters.class)) - .map(MojoParameters::value) - .map(Arrays::asList) - .ifPresent(mojoParameters::addAll); - Class holder = parameterContext.getTarget().get().getClass(); PluginDescriptor descriptor = extensionContext .getStore(ExtensionContext.Namespace.GLOBAL) .get(PluginDescriptor.class, PluginDescriptor.class); - return lookupMojo(holder, injectMojo, mojoParameters, descriptor); + Model model = + extensionContext.getStore(ExtensionContext.Namespace.GLOBAL).get(Model.class, Model.class); + InjectMojo parameterInjectMojo = + parameterContext.getAnnotatedElement().getAnnotation(InjectMojo.class); + String goal; + if (parameterInjectMojo != null) { + String pom = parameterInjectMojo.pom(); + if (pom != null && !pom.isEmpty()) { + try (Reader r = openPomUrl(holder, pom, new Path[1])) { + Model localModel = new MavenStaxReader().read(r); + model = new MavenMerger().merge(localModel, model, false, null); + model = new DefaultModelPathTranslator(new DefaultPathTranslator()) + .alignToBaseDirectory(model, Paths.get(getBasedir()), null); + } + } + goal = parameterInjectMojo.goal(); + } else { + InjectMojo methodInjectMojo = AnnotationSupport.findAnnotation( + parameterContext.getDeclaringExecutable(), InjectMojo.class) + .orElse(null); + if (methodInjectMojo != null) { + goal = methodInjectMojo.goal(); + } else { + goal = getGoalFromMojoImplementationClass( + parameterContext.getParameter().getType()); + } + } + + Set mojoParameters = new LinkedHashSet<>(); + for (AnnotatedElement ae : + Arrays.asList(parameterContext.getDeclaringExecutable(), parameterContext.getAnnotatedElement())) { + mojoParameters.addAll(AnnotationSupport.findRepeatableAnnotations(ae, MojoParameter.class)); + } + String[] coord = mojoCoordinates(goal); + + XmlNode pluginConfiguration = model.getBuild().getPlugins().stream() + .filter(p -> + Objects.equals(p.getGroupId(), coord[0]) && Objects.equals(p.getArtifactId(), coord[1])) + .map(ConfigurationContainer::getConfiguration) + .findFirst() + .orElseGet(() -> new XmlNodeImpl("config")); + List children = mojoParameters.stream() + .map(mp -> new XmlNodeImpl(mp.name(), mp.value())) + .collect(Collectors.toList()); + XmlNode config = new XmlNodeImpl("configuration", null, null, children, null); + pluginConfiguration = XmlNode.merge(config, pluginConfiguration); + + // load default config + // pluginkey = groupId : artifactId : version : goal + Mojo mojo = lookup(Mojo.class, coord[0] + ":" + coord[1] + ":" + coord[2] + ":" + coord[3]); + for (MojoDescriptor mojoDescriptor : descriptor.getMojos()) { + if (Objects.equals(mojoDescriptor.getGoal(), coord[3])) { + if (pluginConfiguration != null) { + pluginConfiguration = finalizeConfig(pluginConfiguration, mojoDescriptor); + } + } + } + + Session session = getInjector().getInstance(Session.class); + Project project = getInjector().getInstance(Project.class); + MojoExecution mojoExecution = getInjector().getInstance(MojoExecution.class); + ExpressionEvaluator evaluator = new WrapEvaluator( + getInjector(), new PluginParameterExpressionEvaluatorV4(session, project, mojoExecution)); + + EnhancedComponentConfigurator configurator = new EnhancedComponentConfigurator(); + configurator.configureComponent( + mojo, new XmlPlexusConfiguration(pluginConfiguration), evaluator, null, null); + return mojo; } catch (Exception e) { - throw new ParameterResolutionException("Unable to resolve parameter", e); + throw new ParameterResolutionException("Unable to resolve mojo", e); } } + /** + * The @Mojo annotation is only retained in the class file, not at runtime, + * so we need to actually read the class file with ASM to find the annotation and + * the goal. + */ + private static String getGoalFromMojoImplementationClass(Class cl) throws IOException { + return cl.getAnnotation(Named.class).value(); + } + @Override public void beforeEach(ExtensionContext context) throws Exception { - // TODO provide protected setters in PlexusExtension - Field field = PlexusExtension.class.getDeclaredField("basedir"); - field.setAccessible(true); - field.set(null, getBasedir()); - field = PlexusExtension.class.getDeclaredField("context"); - field.setAccessible(true); - field.set(this, context); - - getContainer().addComponent(getContainer(), PlexusContainer.class.getName()); - - ((DefaultPlexusContainer) getContainer()).addPlexusInjector(Collections.emptyList(), binder -> { - binder.install(ProviderMethodsModule.forObject(context.getRequiredTestInstance())); - binder.requestInjection(context.getRequiredTestInstance()); - binder.bind(Log.class).toInstance(new DefaultLog(LoggerFactory.getLogger("anonymous"))); - }); + if (pluginBasedir == null) { + pluginBasedir = MavenDIExtension.getBasedir(); + } + basedir = AnnotationSupport.findAnnotation(context.getElement().get(), Basedir.class) + .map(Basedir::value) + .orElse(pluginBasedir); + if (basedir != null) { + if (basedir.isEmpty()) { + basedir = pluginBasedir + "/target/tests/" + + context.getRequiredTestClass().getSimpleName() + "/" + + context.getRequiredTestMethod().getName(); + } else { + basedir = basedir.replace("${basedir}", pluginBasedir); + } + } - Map map = getContainer().getContext().getContextData(); + setContext(context); + + /* + binder.install(ProviderMethodsModule.forObject(context.getRequiredTestInstance())); + binder.requestInjection(context.getRequiredTestInstance()); + binder.bind(Log.class).toInstance(new DefaultLog(LoggerFactory.getLogger("anonymous"))); + binder.bind(ExtensionContext.class).toInstance(context); + // Load maven 4 api Services interfaces and try to bind them to the (possible) mock instances + // returned by the (possibly) mock InternalSession + try { + for (ClassPath.ClassInfo clazz : + ClassPath.from(getClassLoader()).getAllClasses()) { + if ("org.apache.maven.api.services".equals(clazz.getPackageName())) { + Class load = clazz.load(); + if (Service.class.isAssignableFrom(load)) { + Class svc = (Class) load; + binder.bind(svc).toProvider(() -> { + try { + return getContainer() + .lookup(InternalSession.class) + .getService(svc); + } catch (ComponentLookupException e) { + throw new RuntimeException("Unable to lookup service " + svc.getName()); + } + }); + } + } + } + } catch (Exception e) { + throw new RuntimeException("Unable to bind session services", e); + } + + */ + + Path basedirPath = Paths.get(getBasedir()); + + InjectMojo mojo = AnnotationSupport.findAnnotation(context.getElement().get(), InjectMojo.class) + .orElse(null); + Model defaultModel = Model.newBuilder() + .groupId("myGroupId") + .artifactId("myArtifactId") + .version("1.0-SNAPSHOT") + .packaging("jar") + .build(Build.newBuilder() + .directory(basedirPath.resolve("target").toString()) + .outputDirectory(basedirPath.resolve("target/classes").toString()) + .sourceDirectory(basedirPath.resolve("src/main/java").toString()) + .testSourceDirectory( + basedirPath.resolve("src/test/java").toString()) + .testOutputDirectory( + basedirPath.resolve("target/test-classes").toString()) + .build()) + .build(); + Path[] modelPath = new Path[] {null}; + Model tmodel = null; + if (mojo != null) { + String pom = mojo.pom(); + if (pom != null && !pom.isEmpty()) { + try (Reader r = openPomUrl(context.getRequiredTestClass(), pom, modelPath)) { + tmodel = new MavenStaxReader().read(r); + } + } else { + Path pomPath = basedirPath.resolve("pom.xml"); + if (Files.exists(pomPath)) { + try (Reader r = Files.newBufferedReader(pomPath)) { + tmodel = new MavenStaxReader().read(r); + modelPath[0] = pomPath; + } + } + } + } + Model model; + if (tmodel == null) { + model = defaultModel; + } else { + model = new MavenMerger().merge(tmodel, defaultModel, false, null); + } + tmodel = new DefaultModelPathTranslator(new DefaultPathTranslator()) + .alignToBaseDirectory(tmodel, Paths.get(getBasedir()), null); + context.getStore(ExtensionContext.Namespace.GLOBAL).put(Model.class, tmodel); + // mojo execution + // Map map = getInjector().getContext().getContextData(); + PluginDescriptor pluginDescriptor; ClassLoader classLoader = context.getRequiredTestClass().getClassLoader(); - try (InputStream is = Objects.requireNonNull( + try (InputStream is = requireNonNull( classLoader.getResourceAsStream(getPluginDescriptorLocation()), "Unable to find plugin descriptor: " + getPluginDescriptorLocation()); - Reader reader = new BufferedReader(new XmlStreamReader(is)); - InterpolationFilterReader interpolationReader = new InterpolationFilterReader(reader, map, "${", "}")) { + Reader reader = new BufferedReader(new XmlStreamReader(is))) { + // new InterpolationFilterReader(reader, map, "${", "}"); + pluginDescriptor = new PluginDescriptorStaxReader().read(reader); + } + context.getStore(ExtensionContext.Namespace.GLOBAL).put(PluginDescriptor.class, pluginDescriptor); + // for (ComponentDescriptor desc : pluginDescriptor.getComponents()) { + // getContainer().addComponentDescriptor(desc); + // } + + @SuppressWarnings({"unused", "MagicNumber"}) + class Foo { + + @Provides + @Singleton + @Priority(-10) + private InternalSession createSession() { + return SessionMock.getMockSession(getBasedir()); + } + + @Provides + @Singleton + @Priority(-10) + private Project createProject(InternalSession s) { + ProjectStub stub = new ProjectStub(); + if (!"pom".equals(model.getPackaging())) { + ArtifactStub artifact = new ArtifactStub( + model.getGroupId(), model.getArtifactId(), "", model.getVersion(), model.getPackaging()); + stub.setMainArtifact(artifact); + } + stub.setModel(model); + stub.setBasedir(Paths.get(MojoExtension.getBasedir())); + stub.setPomPath(modelPath[0]); + s.getService(ArtifactManager.class).setPath(stub.getPomArtifact(), modelPath[0]); + return stub; + } + + @Provides + @Singleton + @Priority(-10) + private MojoExecution createMojoExecution() { + MojoExecutionStub mes = new MojoExecutionStub("executionId", null); + if (mojo != null) { + String goal = mojo.goal(); + int idx = goal.lastIndexOf(':'); + if (idx >= 0) { + goal = goal.substring(idx + 1); + } + mes.setGoal(goal); + for (MojoDescriptor md : pluginDescriptor.getMojos()) { + if (goal.equals(md.getGoal())) { + mes.setDescriptor(md); + } + } + requireNonNull(mes.getDescriptor()); + } + PluginStub plugin = new PluginStub(); + plugin.setDescriptor(pluginDescriptor); + mes.setPlugin(plugin); + return mes; + } + + @Provides + @Singleton + @Priority(-10) + private Log createLog() { + return new DefaultLog(LoggerFactory.getLogger("anonymous")); + } - PluginDescriptor pluginDescriptor = new PluginDescriptorBuilder().build(interpolationReader); + @Provides + static RepositorySystemSupplier newRepositorySystemSupplier() { + return new RepositorySystemSupplier(); + } + + @Provides + static RepositorySystem newRepositorySystem(RepositorySystemSupplier repositorySystemSupplier) { + return repositorySystemSupplier.getRepositorySystem(); + } + + @Provides + @Priority(10) + static RepositoryFactory newRepositoryFactory(Session session) { + return session.getService(RepositoryFactory.class); + } + + @Provides + @Priority(10) + static VersionParser newVersionParser(Session session) { + return session.getService(VersionParser.class); + } + + @Provides + @Priority(10) + static LocalRepositoryManager newLocalRepositoryManager(Session session) { + return session.getService(LocalRepositoryManager.class); + } + + @Provides + @Priority(10) + static ArtifactInstaller newArtifactInstaller(Session session) { + return session.getService(ArtifactInstaller.class); + } + + @Provides + @Priority(10) + static ArtifactDeployer newArtifactDeployer(Session session) { + return session.getService(ArtifactDeployer.class); + } + + @Provides + @Priority(10) + static ArtifactManager newArtifactManager(Session session) { + return session.getService(ArtifactManager.class); + } - context.getStore(ExtensionContext.Namespace.GLOBAL).put(PluginDescriptor.class, pluginDescriptor); + @Provides + @Priority(10) + static ProjectManager newProjectManager(Session session) { + return session.getService(ProjectManager.class); + } - for (ComponentDescriptor desc : pluginDescriptor.getComponents()) { - getContainer().addComponentDescriptor(desc); + @Provides + @Priority(10) + static ArtifactFactory newArtifactFactory(Session session) { + return session.getService(ArtifactFactory.class); + } + + @Provides + @Priority(10) + static ProjectBuilder newProjectBuilder(Session session) { + return session.getService(ProjectBuilder.class); + } + + @Provides + @Priority(10) + static ModelXmlFactory newModelXmlFactory(Session session) { + return session.getService(ModelXmlFactory.class); } } - } - protected String getPluginDescriptorLocation() { - return "META-INF/maven/plugin.xml"; + getInjector().bindInstance(Foo.class, new Foo()); + + getInjector().injectInstance(context.getRequiredTestInstance()); + + // SessionScope sessionScope = getInjector().getInstance(SessionScope.class); + // sessionScope.enter(); + // sessionScope.seed(Session.class, s); + // sessionScope.seed(InternalSession.class, s); + + // MojoExecutionScope mojoExecutionScope = getInjector().getInstance(MojoExecutionScope.class); + // mojoExecutionScope.enter(); + // mojoExecutionScope.seed(Project.class, p); + // mojoExecutionScope.seed(MojoExecution.class, me); } - private Mojo lookupMojo( - Class holder, - InjectMojo injectMojo, - Collection mojoParameters, - PluginDescriptor descriptor) - throws Exception { - String goal = injectMojo.goal(); - String pom = injectMojo.pom(); - String[] coord = mojoCoordinates(goal); - Xpp3Dom pomDom; + private Reader openPomUrl(Class holder, String pom, Path[] modelPath) throws IOException { if (pom.startsWith("file:")) { Path path = Paths.get(getBasedir()).resolve(pom.substring("file:".length())); - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(path.toFile())); + modelPath[0] = path; + return Files.newBufferedReader(path); } else if (pom.startsWith("classpath:")) { URL url = holder.getResource(pom.substring("classpath:".length())); if (url == null) { throw new IllegalStateException("Unable to find pom on classpath: " + pom); } - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(url.openStream())); + return new XmlStreamReader(url.openStream()); } else if (pom.contains("")) { - pomDom = Xpp3DomBuilder.build(new StringReader(pom)); + return new StringReader(pom); } else { Path path = Paths.get(getBasedir()).resolve(pom); - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(path.toFile())); - } - XmlNode pluginConfiguration = extractPluginConfiguration(coord[1], pomDom); - if (!mojoParameters.isEmpty()) { - List children = mojoParameters.stream() - .map(mp -> new XmlNodeImpl(mp.name(), mp.value())) - .collect(Collectors.toList()); - XmlNode config = new XmlNodeImpl("configuration", null, null, children, null); - pluginConfiguration = XmlNode.merge(config, pluginConfiguration); + modelPath[0] = path; + return Files.newBufferedReader(path); } - Mojo mojo = lookupMojo(coord, pluginConfiguration, descriptor); - return mojo; + } + + protected String getPluginDescriptorLocation() { + return "META-INF/maven/plugin.xml"; } protected String[] mojoCoordinates(String goal) throws Exception { if (goal.matches(".*:.*:.*:.*")) { return goal.split(":"); } else { - Path pluginPom = Paths.get(getBasedir(), "pom.xml"); - Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(pluginPom.toFile())); + Path pluginPom = Paths.get(getPluginBasedir(), "pom.xml"); + Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(Files.newBufferedReader(pluginPom)); String artifactId = pluginPomDom.getChild("artifactId").getValue(); String groupId = resolveFromRootThenParent(pluginPomDom, "groupId"); String version = resolveFromRootThenParent(pluginPomDom, "version"); @@ -217,55 +508,11 @@ protected String[] mojoCoordinates(String goal) throws Exception { } } - /** - * lookup the mojo while we have all the relevent information - */ - protected Mojo lookupMojo(String[] coord, XmlNode pluginConfiguration, PluginDescriptor descriptor) - throws Exception { - // pluginkey = groupId : artifactId : version : goal - Mojo mojo = lookup(Mojo.class, coord[0] + ":" + coord[1] + ":" + coord[2] + ":" + coord[3]); - for (MojoDescriptor mojoDescriptor : descriptor.getMojos()) { - if (Objects.equals( - mojoDescriptor.getImplementation(), mojo.getClass().getName())) { - if (pluginConfiguration != null) { - pluginConfiguration = finalizeConfig(pluginConfiguration, mojoDescriptor); - } - } - } - if (pluginConfiguration != null) { - Session session = getContainer().lookup(Session.class); - Project project; - try { - project = getContainer().lookup(Project.class); - } catch (ComponentLookupException e) { - project = null; - } - org.apache.maven.plugin.MojoExecution mojoExecution; - try { - MojoExecution me = getContainer().lookup(MojoExecution.class); - mojoExecution = new org.apache.maven.plugin.MojoExecution( - new org.apache.maven.model.Plugin(me.getPlugin()), me.getGoal(), me.getExecutionId()); - } catch (ComponentLookupException e) { - mojoExecution = null; - } - ExpressionEvaluator evaluator = new WrapEvaluator( - getContainer(), new PluginParameterExpressionEvaluatorV4(session, project, mojoExecution)); - ComponentConfigurator configurator = new EnhancedComponentConfigurator(); - configurator.configureComponent( - mojo, - new XmlPlexusConfiguration(new Xpp3Dom(pluginConfiguration)), - evaluator, - getContainer().getContainerRealm()); - } - - return mojo; - } - private XmlNode finalizeConfig(XmlNode config, MojoDescriptor mojoDescriptor) { List children = new ArrayList<>(); if (mojoDescriptor != null && mojoDescriptor.getParameters() != null) { - XmlNode defaultConfiguration = - MojoDescriptorCreator.convert(mojoDescriptor).getDom(); + XmlNode defaultConfiguration; + defaultConfiguration = MojoDescriptorCreator.convert(mojoDescriptor); for (Parameter parameter : mojoDescriptor.getParameters()) { XmlNode parameterConfiguration = config.getChild(parameter.getName()); if (parameterConfiguration == null) { @@ -275,10 +522,10 @@ private XmlNode finalizeConfig(XmlNode config, MojoDescriptor mojoDescriptor) { parameterConfiguration = XmlNode.merge(parameterConfiguration, parameterDefaults, Boolean.TRUE); if (parameterConfiguration != null) { Map attributes = new HashMap<>(parameterConfiguration.getAttributes()); - if (isEmpty(parameterConfiguration.getAttribute("implementation")) - && !isEmpty(parameter.getImplementation())) { - attributes.put("implementation", parameter.getImplementation()); - } + // if (isEmpty(parameterConfiguration.getAttribute("implementation")) + // && !isEmpty(parameter.getImplementation())) { + // attributes.put("implementation", parameter.getImplementation()); + // } parameterConfiguration = new XmlNodeImpl( parameter.getName(), parameterConfiguration.getValue(), @@ -380,18 +627,18 @@ public static Map getVariablesAndValuesFromObject(Class clazz public static void setVariableValueToObject(Object object, String variable, Object value) throws IllegalAccessException { Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); - Objects.requireNonNull(field, "Field " + variable + " not found"); + requireNonNull(field, "Field " + variable + " not found"); field.setAccessible(true); field.set(object, value); } static class WrapEvaluator implements TypeAwareExpressionEvaluator { - private final PlexusContainer container; + private final Injector injector; private final TypeAwareExpressionEvaluator evaluator; - WrapEvaluator(PlexusContainer container, TypeAwareExpressionEvaluator evaluator) { - this.container = container; + WrapEvaluator(Injector injector, TypeAwareExpressionEvaluator evaluator) { + this.injector = injector; this.evaluator = evaluator; } @@ -407,8 +654,8 @@ public Object evaluate(String expression, Class type) throws ExpressionEvalua String expr = stripTokens(expression); if (expr != null) { try { - value = container.lookup(type, expr); - } catch (ComponentLookupException e) { + value = injector.getInstance(Key.of(type, expr)); + } catch (DIException e) { // nothing } } @@ -428,4 +675,35 @@ public File alignToBaseDirectory(File path) { return evaluator.alignToBaseDirectory(path); } } + + /* + private Scope getScopeInstanceOrNull(final Injector injector, final Binding binding) { + return binding.acceptScopingVisitor(new DefaultBindingScopingVisitor() { + + @Override + public Scope visitScopeAnnotation(Class scopeAnnotation) { + throw new RuntimeException(String.format( + "I don't know how to handle the scopeAnnotation: %s", scopeAnnotation.getCanonicalName())); + } + + @Override + public Scope visitNoScoping() { + if (binding instanceof LinkedKeyBinding) { + Binding childBinding = injector.getBinding(((LinkedKeyBinding) binding).getLinkedKey()); + return getScopeInstanceOrNull(injector, childBinding); + } + return null; + } + + @Override + public Scope visitEagerSingleton() { + return Scopes.SINGLETON; + } + + public Scope visitScope(Scope scope) { + return scope; + } + }); + }*/ + } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameter.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameter.java index 2a28f48..8c37804 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameter.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameter.java @@ -18,6 +18,7 @@ */ package org.apache.maven.api.plugin.testing; +import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -27,6 +28,7 @@ */ @Retention(RetentionPolicy.RUNTIME) @Repeatable(MojoParameters.class) +@Inherited public @interface MojoParameter { String name(); diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameters.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameters.java index 434abe1..373c926 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameters.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameters.java @@ -18,6 +18,7 @@ */ package org.apache.maven.api.plugin.testing; +import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -25,6 +26,7 @@ * Mojo parameters container */ @Retention(RetentionPolicy.RUNTIME) +@Inherited public @interface MojoParameters { MojoParameter[] value(); } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ResolverExpressionEvaluatorStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ResolverExpressionEvaluatorStub.java index 4461071..1ca785d 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ResolverExpressionEvaluatorStub.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ResolverExpressionEvaluatorStub.java @@ -21,11 +21,9 @@ import java.io.File; import java.util.Map; -import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; -import org.codehaus.plexus.testing.PlexusExtension; import org.eclipse.aether.repository.LocalRepository; /** @@ -81,14 +79,14 @@ public Object evaluate(String expr, Class type) throws ExpressionEvaluationEx return expression.contains("$$") ? expression.replaceAll("\\$\\$", "\\$") : expression; } else { if ("basedir".equals(expression) || "project.basedir".equals(expression)) { - value = PlexusExtension.getBasedir(); + value = MojoExtension.getBasedir(); } else if (expression.startsWith("basedir") || expression.startsWith("project.basedir")) { int pathSeparator = expression.indexOf("/"); if (pathSeparator > 0) { - value = PlexusTestCase.getBasedir() + expression.substring(pathSeparator); + value = MojoExtension.getBasedir() + expression.substring(pathSeparator); } } else if ("localRepository".equals(expression)) { - File localRepo = new File(PlexusTestCase.getBasedir(), "target/local-repo"); + File localRepo = new File(MojoExtension.getBasedir(), "target/local-repo"); return new LocalRepository("file://" + localRepo.getAbsolutePath()); } if (value == null && properties != null && properties.containsKey(expression)) { @@ -109,12 +107,12 @@ private String stripTokens(String expr) { /** {@inheritDoc} */ @Override public File alignToBaseDirectory(File file) { - if (file.getAbsolutePath().startsWith(PlexusExtension.getBasedir())) { + if (file.getAbsolutePath().startsWith(MojoExtension.getBasedir())) { return file; } else if (file.isAbsolute()) { return file; } else { - return new File(PlexusExtension.getBasedir(), file.getPath()); + return new File(MojoExtension.getBasedir(), file.getPath()); } } } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ArtifactStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ArtifactStub.java index 59be14f..b9b6416 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ArtifactStub.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ArtifactStub.java @@ -23,9 +23,11 @@ import org.apache.maven.api.Artifact; import org.apache.maven.api.ArtifactCoordinate; import org.apache.maven.api.Version; -import org.apache.maven.api.VersionRange; +import org.apache.maven.api.VersionConstraint; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.internal.impl.DefaultVersionParser; +import org.apache.maven.repository.internal.DefaultModelVersionParser; +import org.eclipse.aether.util.version.GenericVersionScheme; /** * @@ -35,6 +37,7 @@ public class ArtifactStub implements Artifact { private String artifactId; private String classifier; private String version; + private String baseVersion; private String extension; public ArtifactStub() { @@ -86,13 +89,21 @@ public void setClassifier(String classifier) { @Nonnull @Override public Version getVersion() { - return new DefaultVersionParser().parseVersion(version); + return getParser().parseVersion(version); } public void setVersion(String version) { this.version = version; } + public Version getBaseVersion() { + return getParser().parseVersion(baseVersion != null ? baseVersion : version); + } + + public void setBaseVersion(String baseVersion) { + this.baseVersion = baseVersion; + } + @Nonnull @Override public String getExtension() { @@ -127,8 +138,8 @@ public String getClassifier() { } @Override - public VersionRange getVersion() { - return new DefaultVersionParser().parseVersionRange(version); + public VersionConstraint getVersion() { + return getParser().parseVersionConstraint(version); } @Override @@ -169,4 +180,8 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(groupId, artifactId, classifier, version, extension); } + + private static DefaultVersionParser getParser() { + return new DefaultVersionParser(new DefaultModelVersionParser(new GenericVersionScheme())); + } } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/MojoExecutionStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/MojoExecutionStub.java index a2d2b5b..2619b75 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/MojoExecutionStub.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/MojoExecutionStub.java @@ -21,24 +21,28 @@ import java.util.Optional; import org.apache.maven.api.MojoExecution; -import org.apache.maven.api.model.Plugin; +import org.apache.maven.api.Plugin; +import org.apache.maven.api.model.PluginExecution; +import org.apache.maven.api.plugin.descriptor.MojoDescriptor; import org.apache.maven.api.xml.XmlNode; /** * Stub for {@link MojoExecution}. */ public class MojoExecutionStub implements MojoExecution { - private final String artifactId; - private final String executionId; - private final String goal; - private final XmlNode dom; + private String executionId; + private String goal; + private XmlNode dom; + private Plugin plugin = new PluginStub(); + private PluginExecution model; + private MojoDescriptor descriptor; + private String lifecyclePhase; - public MojoExecutionStub(String artifactId, String executionId, String goal) { - this(artifactId, executionId, goal, null); + public MojoExecutionStub(String executionId, String goal) { + this(executionId, goal, null); } - public MojoExecutionStub(String artifactId, String executionId, String goal, XmlNode dom) { - this.artifactId = artifactId; + public MojoExecutionStub(String executionId, String goal, XmlNode dom) { this.executionId = executionId; this.goal = goal; this.dom = dom; @@ -46,7 +50,22 @@ public MojoExecutionStub(String artifactId, String executionId, String goal, Xml @Override public Plugin getPlugin() { - return Plugin.newBuilder().artifactId(artifactId).build(); + return plugin; + } + + @Override + public PluginExecution getModel() { + return model; + } + + @Override + public MojoDescriptor getDescriptor() { + return descriptor; + } + + @Override + public String getLifecyclePhase() { + return lifecyclePhase; } @Override @@ -63,4 +82,32 @@ public String getGoal() { public Optional getConfiguration() { return Optional.ofNullable(dom); } + + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + public void setGoal(String goal) { + this.goal = goal; + } + + public void setDom(XmlNode dom) { + this.dom = dom; + } + + public void setPlugin(Plugin plugin) { + this.plugin = plugin; + } + + public void setModel(PluginExecution model) { + this.model = model; + } + + public void setDescriptor(MojoDescriptor descriptor) { + this.descriptor = descriptor; + } + + public void setLifecyclePhase(String lifecyclePhase) { + this.lifecyclePhase = lifecyclePhase; + } } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/PluginStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/PluginStub.java new file mode 100644 index 0000000..b7b4cfc --- /dev/null +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/PluginStub.java @@ -0,0 +1,102 @@ +/* + * 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.plugin.testing.stubs; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.apache.maven.api.Artifact; +import org.apache.maven.api.Dependency; +import org.apache.maven.api.Plugin; +import org.apache.maven.api.plugin.descriptor.PluginDescriptor; +import org.apache.maven.api.plugin.descriptor.lifecycle.Lifecycle; + +public class PluginStub implements Plugin { + + org.apache.maven.api.model.Plugin model; + PluginDescriptor descriptor; + List lifecycles = Collections.emptyList(); + ClassLoader classLoader; + Artifact artifact; + List dependencies = Collections.emptyList(); + Map dependenciesMap = Collections.emptyMap(); + + @Override + public org.apache.maven.api.model.Plugin getModel() { + return model; + } + + public void setModel(org.apache.maven.api.model.Plugin model) { + this.model = model; + } + + @Override + public PluginDescriptor getDescriptor() { + return descriptor; + } + + public void setDescriptor(PluginDescriptor descriptor) { + this.descriptor = descriptor; + } + + @Override + public List getLifecycles() { + return lifecycles; + } + + public void setLifecycles(List lifecycles) { + this.lifecycles = lifecycles; + } + + @Override + public ClassLoader getClassLoader() { + return classLoader; + } + + public void setClassLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + } + + @Override + public Artifact getArtifact() { + return artifact; + } + + public void setArtifact(Artifact artifact) { + this.artifact = artifact; + } + + @Override + public List getDependencies() { + return dependencies; + } + + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + public Map getDependenciesMap() { + return dependenciesMap; + } + + public void setDependenciesMap(Map dependenciesMap) { + this.dependenciesMap = dependenciesMap; + } +} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ProjectStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ProjectStub.java index b3624cf..fd37fa5 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ProjectStub.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ProjectStub.java @@ -18,18 +18,13 @@ */ package org.apache.maven.api.plugin.testing.stubs; -import java.io.File; import java.nio.file.Path; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -import org.apache.maven.api.Artifact; -import org.apache.maven.api.DependencyCoordinate; -import org.apache.maven.api.Project; -import org.apache.maven.api.RemoteRepository; +import java.util.*; + +import org.apache.maven.api.*; import org.apache.maven.api.annotations.Nonnull; import org.apache.maven.api.model.Model; +import org.apache.maven.api.model.PluginContainer; /** * @author Olivier Lamy @@ -40,10 +35,11 @@ public class ProjectStub implements Project { private Model model = Model.newInstance(); private Path basedir; - private File pomPath; + private Path pomPath; private boolean topProject; - private Artifact artifact; private Path rootDirectory; + private Map properties = new HashMap<>(); + private Artifact mainArtifact; public void setModel(Model model) { this.model = model; @@ -73,14 +69,59 @@ public String getName() { @Nonnull @Override - public String getPackaging() { - return model.getPackaging(); - } - - @Nonnull - @Override - public Artifact getArtifact() { - return artifact; + public Packaging getPackaging() { + return new Packaging() { + @Override + public String id() { + return model.getPackaging(); + } + + @Override + public Type type() { + return new Type() { + @Override + public String id() { + return model.getPackaging(); + } + + @Override + public Language getLanguage() { + return null; + } + + @Override + public String getExtension() { + return model.getPackaging(); + } + + @Override + public String getClassifier() { + return ""; + } + + @Override + public boolean isIncludesDependencies() { + return false; + } + + @Override + public Set getPathTypes() { + return Set.of(); + } + }; + } + + @Override + public Map plugins() { + return Map.of(); + } + }; + } + + @Override + public List getArtifacts() { + Artifact pomArtifact = new ArtifactStub(getGroupId(), getArtifactId(), "", getVersion(), "pom"); + return mainArtifact != null ? Arrays.asList(pomArtifact, mainArtifact) : Arrays.asList(pomArtifact); } @Nonnull @@ -91,8 +132,8 @@ public Model getModel() { @Nonnull @Override - public Optional getPomPath() { - return Optional.ofNullable(pomPath).map(File::toPath); + public Path getPomPath() { + return pomPath; } @Nonnull @@ -108,17 +149,8 @@ public List getManagedDependencies() { } @Override - public Optional getBasedir() { - return Optional.ofNullable(basedir); - } - - public void setBasedir(Path basedir) { - this.basedir = basedir; - } - - @Override - public boolean isExecutionRoot() { - return isTopProject(); + public Path getBasedir() { + return basedir; } @Override @@ -126,16 +158,6 @@ public Optional getParent() { return Optional.empty(); } - @Override - public List getRemoteProjectRepositories() { - return Collections.emptyList(); - } - - @Override - public List getRemotePluginRepositories() { - return Collections.emptyList(); - } - @Override public boolean isTopProject() { return topProject; @@ -151,43 +173,74 @@ public Path getRootDirectory() { return rootDirectory; } - public void setGroupId(String groupId) { + // + // Setters + // + + public ProjectStub setBasedir(Path basedir) { + this.basedir = basedir; + return this; + } + + public ProjectStub setGroupId(String groupId) { model = model.withGroupId(groupId); + return this; } - public void setArtifactId(String artifactId) { + public ProjectStub setArtifactId(String artifactId) { model = model.withArtifactId(artifactId); + return this; } - public void setVersion(String version) { + public ProjectStub setVersion(String version) { model = model.withVersion(version); + return this; } - public void setName(String name) { + public ProjectStub setName(String name) { model = model.withName(name); + return this; + } + + public ProjectStub setDescription(String desc) { + model = model.withDescription(desc); + return this; } - public void setPackaging(String packaging) { + public ProjectStub setPackaging(String packaging) { model = model.withPackaging(packaging); + return this; } - public void setArtifact(Artifact artifact) { - this.artifact = artifact; + public ProjectStub setMainArtifact(Artifact mainArtifact) { + this.mainArtifact = mainArtifact; + return this; } - public void setPomPath(File pomPath) { + public ProjectStub setPomPath(Path pomPath) { this.pomPath = pomPath; + return this; } - public void setTopProject(boolean topProject) { + public ProjectStub setTopProject(boolean topProject) { this.topProject = topProject; + return this; } - public void setMavenModel(org.apache.maven.model.Model model) { + public ProjectStub setMavenModel(org.apache.maven.model.Model model) { this.model = model.getDelegate(); + return this; } - public void setRootDirectory(Path rootDirectory) { + public ProjectStub setRootDirectory(Path rootDirectory) { this.rootDirectory = rootDirectory; + return this; + } + + public ProjectStub addProperty(String key, String value) { + Map props = new HashMap<>(model.getProperties()); + props.put(key, value); + model = model.withProperties(props); + return this; } } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/RepositorySystemSupplier.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/RepositorySystemSupplier.java new file mode 100644 index 0000000..0e709b3 --- /dev/null +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/RepositorySystemSupplier.java @@ -0,0 +1,1069 @@ +/* + * 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.plugin.testing.stubs; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; + +import org.apache.maven.api.services.ModelBuilder; +import org.apache.maven.internal.impl.DefaultModelUrlNormalizer; +import org.apache.maven.internal.impl.DefaultModelVersionParser; +import org.apache.maven.internal.impl.DefaultModelXmlFactory; +import org.apache.maven.internal.impl.DefaultPluginConfigurationExpander; +import org.apache.maven.internal.impl.DefaultSuperPomProvider; +import org.apache.maven.internal.impl.DefaultUrlNormalizer; +import org.apache.maven.internal.impl.model.BuildModelTransformer; +import org.apache.maven.internal.impl.model.DefaultDependencyManagementImporter; +import org.apache.maven.internal.impl.model.DefaultDependencyManagementInjector; +import org.apache.maven.internal.impl.model.DefaultInheritanceAssembler; +import org.apache.maven.internal.impl.model.DefaultModelBuilder; +import org.apache.maven.internal.impl.model.DefaultModelInterpolator; +import org.apache.maven.internal.impl.model.DefaultModelNormalizer; +import org.apache.maven.internal.impl.model.DefaultModelPathTranslator; +import org.apache.maven.internal.impl.model.DefaultModelProcessor; +import org.apache.maven.internal.impl.model.DefaultModelValidator; +import org.apache.maven.internal.impl.model.DefaultModelVersionProcessor; +import org.apache.maven.internal.impl.model.DefaultPathTranslator; +import org.apache.maven.internal.impl.model.DefaultPluginManagementInjector; +import org.apache.maven.internal.impl.model.DefaultProfileInjector; +import org.apache.maven.internal.impl.model.DefaultProfileSelector; +import org.apache.maven.internal.impl.model.DefaultRootLocator; +import org.apache.maven.internal.impl.model.ProfileActivationFilePathInterpolator; +import org.apache.maven.internal.impl.resolver.DefaultArtifactDescriptorReader; +import org.apache.maven.internal.impl.resolver.DefaultVersionRangeResolver; +import org.apache.maven.internal.impl.resolver.DefaultVersionResolver; +import org.apache.maven.internal.impl.resolver.MavenArtifactRelocationSource; +import org.apache.maven.internal.impl.resolver.PluginsMetadataGeneratorFactory; +import org.apache.maven.internal.impl.resolver.SnapshotMetadataGeneratorFactory; +import org.apache.maven.internal.impl.resolver.VersionsMetadataGeneratorFactory; +import org.apache.maven.internal.impl.resolver.relocation.DistributionManagementArtifactRelocationSource; +import org.apache.maven.internal.impl.resolver.relocation.UserPropertiesArtifactRelocationSource; +import org.eclipse.aether.RepositoryListener; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; +import org.eclipse.aether.impl.ArtifactDescriptorReader; +import org.eclipse.aether.impl.ArtifactResolver; +import org.eclipse.aether.impl.DependencyCollector; +import org.eclipse.aether.impl.Deployer; +import org.eclipse.aether.impl.Installer; +import org.eclipse.aether.impl.LocalRepositoryProvider; +import org.eclipse.aether.impl.MetadataGeneratorFactory; +import org.eclipse.aether.impl.MetadataResolver; +import org.eclipse.aether.impl.OfflineController; +import org.eclipse.aether.impl.RemoteRepositoryFilterManager; +import org.eclipse.aether.impl.RemoteRepositoryManager; +import org.eclipse.aether.impl.RepositoryConnectorProvider; +import org.eclipse.aether.impl.RepositoryEventDispatcher; +import org.eclipse.aether.impl.RepositorySystemLifecycle; +import org.eclipse.aether.impl.UpdateCheckManager; +import org.eclipse.aether.impl.UpdatePolicyAnalyzer; +import org.eclipse.aether.impl.VersionRangeResolver; +import org.eclipse.aether.impl.VersionResolver; +import org.eclipse.aether.internal.impl.*; +import org.eclipse.aether.internal.impl.checksum.DefaultChecksumAlgorithmFactorySelector; +import org.eclipse.aether.internal.impl.checksum.Md5ChecksumAlgorithmFactory; +import org.eclipse.aether.internal.impl.checksum.Sha1ChecksumAlgorithmFactory; +import org.eclipse.aether.internal.impl.checksum.Sha256ChecksumAlgorithmFactory; +import org.eclipse.aether.internal.impl.checksum.Sha512ChecksumAlgorithmFactory; +import org.eclipse.aether.internal.impl.checksum.SparseDirectoryTrustedChecksumsSource; +import org.eclipse.aether.internal.impl.checksum.SummaryFileTrustedChecksumsSource; +import org.eclipse.aether.internal.impl.checksum.TrustedToProvidedChecksumsSourceAdapter; +import org.eclipse.aether.internal.impl.collect.DefaultDependencyCollector; +import org.eclipse.aether.internal.impl.collect.DependencyCollectorDelegate; +import org.eclipse.aether.internal.impl.collect.bf.BfDependencyCollector; +import org.eclipse.aether.internal.impl.collect.df.DfDependencyCollector; +import org.eclipse.aether.internal.impl.filter.DefaultRemoteRepositoryFilterManager; +import org.eclipse.aether.internal.impl.filter.GroupIdRemoteRepositoryFilterSource; +import org.eclipse.aether.internal.impl.filter.PrefixesRemoteRepositoryFilterSource; +import org.eclipse.aether.internal.impl.resolution.TrustedChecksumsArtifactResolverPostProcessor; +import org.eclipse.aether.internal.impl.synccontext.DefaultSyncContextFactory; +import org.eclipse.aether.internal.impl.synccontext.named.NameMapper; +import org.eclipse.aether.internal.impl.synccontext.named.NameMappers; +import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactoryAdapterFactory; +import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactoryAdapterFactoryImpl; +import org.eclipse.aether.internal.impl.transport.http.DefaultChecksumExtractor; +import org.eclipse.aether.internal.impl.transport.http.Nx2ChecksumExtractor; +import org.eclipse.aether.internal.impl.transport.http.XChecksumExtractor; +import org.eclipse.aether.named.NamedLockFactory; +import org.eclipse.aether.named.providers.FileLockNamedLockFactory; +import org.eclipse.aether.named.providers.LocalReadWriteLockNamedLockFactory; +import org.eclipse.aether.named.providers.LocalSemaphoreNamedLockFactory; +import org.eclipse.aether.named.providers.NoopNamedLockFactory; +import org.eclipse.aether.spi.artifact.ArtifactPredicateFactory; +import org.eclipse.aether.spi.artifact.decorator.ArtifactDecoratorFactory; +import org.eclipse.aether.spi.artifact.generator.ArtifactGeneratorFactory; +import org.eclipse.aether.spi.checksums.ProvidedChecksumsSource; +import org.eclipse.aether.spi.checksums.TrustedChecksumsSource; +import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; +import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory; +import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactorySelector; +import org.eclipse.aether.spi.connector.checksum.ChecksumPolicyProvider; +import org.eclipse.aether.spi.connector.filter.RemoteRepositoryFilterSource; +import org.eclipse.aether.spi.connector.layout.RepositoryLayoutFactory; +import org.eclipse.aether.spi.connector.layout.RepositoryLayoutProvider; +import org.eclipse.aether.spi.connector.transport.TransporterFactory; +import org.eclipse.aether.spi.connector.transport.TransporterProvider; +import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor; +import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractorStrategy; +import org.eclipse.aether.spi.io.ChecksumProcessor; +import org.eclipse.aether.spi.io.PathProcessor; +import org.eclipse.aether.spi.localrepo.LocalRepositoryManagerFactory; +import org.eclipse.aether.spi.resolution.ArtifactResolverPostProcessor; +import org.eclipse.aether.spi.synccontext.SyncContextFactory; +import org.eclipse.aether.transport.apache.ApacheTransporterFactory; +import org.eclipse.aether.transport.file.FileTransporterFactory; +import org.eclipse.aether.util.version.GenericVersionScheme; +import org.eclipse.aether.version.VersionScheme; + +/** + * A simple memorizing {@link Supplier} of {@link RepositorySystem} instance, that on first call + * supplies lazily constructed instance, and on each subsequent call same instance. Hence, this instance should be + * thrown away immediately once repository system was created and there is no need for more instances. If new + * repository system instance needed, new instance of this class must be created. For proper shut down of returned + * repository system instance(s) use {@link RepositorySystem#shutdown()} method on supplied instance(s). + *

+ * Since Resolver 2.0 this class offers access to various components via public getters, and allows even partial object + * graph construction. + *

+ * Extend this class {@code createXXX()} methods and override to customize, if needed. The contract of this class makes + * sure that these (potentially overridden) methods are invoked only once, and instance created by those methods are + * memorized and kept as long as supplier instance is kept open. + *

+ * This class is not thread safe and must be used from one thread only, while the constructed {@link RepositorySystem} + * is thread safe. + *

+ * Important: Given the instance of supplier memorizes the supplier {@link RepositorySystem} instance it supplies, + * their lifecycle is shared as well: once supplied repository system is shut-down, this instance becomes closed as + * well. Any subsequent {@code getXXX} method invocation attempt will fail with {@link IllegalStateException}. + */ +public class RepositorySystemSupplier implements Supplier { + private final AtomicBoolean closed = new AtomicBoolean(false); + + public RepositorySystemSupplier() {} + + private void checkClosed() { + if (closed.get()) { + throw new IllegalStateException("Supplier is closed"); + } + } + + private PathProcessor pathProcessor; + + public final PathProcessor getPathProcessor() { + checkClosed(); + if (pathProcessor == null) { + pathProcessor = createPathProcessor(); + } + return pathProcessor; + } + + protected PathProcessor createPathProcessor() { + return new DefaultPathProcessor(); + } + + private ChecksumProcessor checksumProcessor; + + public final ChecksumProcessor getChecksumProcessor() { + checkClosed(); + if (checksumProcessor == null) { + checksumProcessor = createChecksumProcessor(); + } + return checksumProcessor; + } + + protected ChecksumProcessor createChecksumProcessor() { + return new DefaultChecksumProcessor(getPathProcessor()); + } + + private TrackingFileManager trackingFileManager; + + public final TrackingFileManager getTrackingFileManager() { + checkClosed(); + if (trackingFileManager == null) { + trackingFileManager = createTrackingFileManager(); + } + return trackingFileManager; + } + + protected TrackingFileManager createTrackingFileManager() { + return new DefaultTrackingFileManager(); + } + + private LocalPathComposer localPathComposer; + + public final LocalPathComposer getLocalPathComposer() { + checkClosed(); + if (localPathComposer == null) { + localPathComposer = createLocalPathComposer(); + } + return localPathComposer; + } + + protected LocalPathComposer createLocalPathComposer() { + return new DefaultLocalPathComposer(); + } + + private LocalPathPrefixComposerFactory localPathPrefixComposerFactory; + + public final LocalPathPrefixComposerFactory getLocalPathPrefixComposerFactory() { + checkClosed(); + if (localPathPrefixComposerFactory == null) { + localPathPrefixComposerFactory = createLocalPathPrefixComposerFactory(); + } + return localPathPrefixComposerFactory; + } + + protected LocalPathPrefixComposerFactory createLocalPathPrefixComposerFactory() { + return new DefaultLocalPathPrefixComposerFactory(); + } + + private RepositorySystemLifecycle repositorySystemLifecycle; + + public final RepositorySystemLifecycle getRepositorySystemLifecycle() { + checkClosed(); + if (repositorySystemLifecycle == null) { + repositorySystemLifecycle = createRepositorySystemLifecycle(); + repositorySystemLifecycle.addOnSystemEndedHandler(() -> closed.set(true)); + } + return repositorySystemLifecycle; + } + + protected RepositorySystemLifecycle createRepositorySystemLifecycle() { + return new DefaultRepositorySystemLifecycle(); + } + + private OfflineController offlineController; + + public final OfflineController getOfflineController() { + checkClosed(); + if (offlineController == null) { + offlineController = createOfflineController(); + } + return offlineController; + } + + protected OfflineController createOfflineController() { + return new DefaultOfflineController(); + } + + private UpdatePolicyAnalyzer updatePolicyAnalyzer; + + public final UpdatePolicyAnalyzer getUpdatePolicyAnalyzer() { + checkClosed(); + if (updatePolicyAnalyzer == null) { + updatePolicyAnalyzer = createUpdatePolicyAnalyzer(); + } + return updatePolicyAnalyzer; + } + + protected UpdatePolicyAnalyzer createUpdatePolicyAnalyzer() { + return new DefaultUpdatePolicyAnalyzer(); + } + + private ChecksumPolicyProvider checksumPolicyProvider; + + public final ChecksumPolicyProvider getChecksumPolicyProvider() { + checkClosed(); + if (checksumPolicyProvider == null) { + checksumPolicyProvider = createChecksumPolicyProvider(); + } + return checksumPolicyProvider; + } + + protected ChecksumPolicyProvider createChecksumPolicyProvider() { + return new DefaultChecksumPolicyProvider(); + } + + private UpdateCheckManager updateCheckManager; + + public final UpdateCheckManager getUpdateCheckManager() { + checkClosed(); + if (updateCheckManager == null) { + updateCheckManager = createUpdateCheckManager(); + } + return updateCheckManager; + } + + protected UpdateCheckManager createUpdateCheckManager() { + return new DefaultUpdateCheckManager(getTrackingFileManager(), getUpdatePolicyAnalyzer(), getPathProcessor()); + } + + private Map namedLockFactories; + + public final Map getNamedLockFactories() { + checkClosed(); + if (namedLockFactories == null) { + namedLockFactories = createNamedLockFactories(); + } + return namedLockFactories; + } + + protected Map createNamedLockFactories() { + HashMap result = new HashMap<>(); + result.put(NoopNamedLockFactory.NAME, new NoopNamedLockFactory()); + result.put(LocalReadWriteLockNamedLockFactory.NAME, new LocalReadWriteLockNamedLockFactory()); + result.put(LocalSemaphoreNamedLockFactory.NAME, new LocalSemaphoreNamedLockFactory()); + result.put(FileLockNamedLockFactory.NAME, new FileLockNamedLockFactory()); + return result; + } + + private Map nameMappers; + + public final Map getNameMappers() { + checkClosed(); + if (nameMappers == null) { + nameMappers = createNameMappers(); + } + return nameMappers; + } + + protected Map createNameMappers() { + HashMap result = new HashMap<>(); + result.put(NameMappers.STATIC_NAME, NameMappers.staticNameMapper()); + result.put(NameMappers.GAV_NAME, NameMappers.gavNameMapper()); + result.put(NameMappers.DISCRIMINATING_NAME, NameMappers.discriminatingNameMapper()); + result.put(NameMappers.FILE_GAV_NAME, NameMappers.fileGavNameMapper()); + result.put(NameMappers.FILE_HGAV_NAME, NameMappers.fileHashingGavNameMapper()); + return result; + } + + private NamedLockFactoryAdapterFactory namedLockFactoryAdapterFactory; + + public final NamedLockFactoryAdapterFactory getNamedLockFactoryAdapterFactory() { + checkClosed(); + if (namedLockFactoryAdapterFactory == null) { + namedLockFactoryAdapterFactory = createNamedLockFactoryAdapterFactory(); + } + return namedLockFactoryAdapterFactory; + } + + protected NamedLockFactoryAdapterFactory createNamedLockFactoryAdapterFactory() { + return new NamedLockFactoryAdapterFactoryImpl( + getNamedLockFactories(), getNameMappers(), getRepositorySystemLifecycle()); + } + + private SyncContextFactory syncContextFactory; + + public final SyncContextFactory getSyncContextFactory() { + checkClosed(); + if (syncContextFactory == null) { + syncContextFactory = createSyncContextFactory(); + } + return syncContextFactory; + } + + protected SyncContextFactory createSyncContextFactory() { + return new DefaultSyncContextFactory(getNamedLockFactoryAdapterFactory()); + } + + private Map checksumAlgorithmFactories; + + public final Map getChecksumAlgorithmFactories() { + checkClosed(); + if (checksumAlgorithmFactories == null) { + checksumAlgorithmFactories = createChecksumAlgorithmFactories(); + } + return checksumAlgorithmFactories; + } + + protected Map createChecksumAlgorithmFactories() { + HashMap result = new HashMap<>(); + result.put(Sha512ChecksumAlgorithmFactory.NAME, new Sha512ChecksumAlgorithmFactory()); + result.put(Sha256ChecksumAlgorithmFactory.NAME, new Sha256ChecksumAlgorithmFactory()); + result.put(Sha1ChecksumAlgorithmFactory.NAME, new Sha1ChecksumAlgorithmFactory()); + result.put(Md5ChecksumAlgorithmFactory.NAME, new Md5ChecksumAlgorithmFactory()); + return result; + } + + private ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector; + + public final ChecksumAlgorithmFactorySelector getChecksumAlgorithmFactorySelector() { + checkClosed(); + if (checksumAlgorithmFactorySelector == null) { + checksumAlgorithmFactorySelector = createChecksumAlgorithmFactorySelector(); + } + return checksumAlgorithmFactorySelector; + } + + protected ChecksumAlgorithmFactorySelector createChecksumAlgorithmFactorySelector() { + return new DefaultChecksumAlgorithmFactorySelector(getChecksumAlgorithmFactories()); + } + + private ArtifactPredicateFactory artifactPredicateFactory; + + public final ArtifactPredicateFactory getArtifactPredicateFactory() { + checkClosed(); + if (artifactPredicateFactory == null) { + artifactPredicateFactory = createArtifactPredicateFactory(); + } + return artifactPredicateFactory; + } + + protected ArtifactPredicateFactory createArtifactPredicateFactory() { + return new DefaultArtifactPredicateFactory(getChecksumAlgorithmFactorySelector()); + } + + private Map repositoryLayoutFactories; + + public final Map getRepositoryLayoutFactories() { + checkClosed(); + if (repositoryLayoutFactories == null) { + repositoryLayoutFactories = createRepositoryLayoutFactories(); + } + return repositoryLayoutFactories; + } + + protected Map createRepositoryLayoutFactories() { + HashMap result = new HashMap<>(); + result.put( + Maven2RepositoryLayoutFactory.NAME, + new Maven2RepositoryLayoutFactory( + getChecksumAlgorithmFactorySelector(), getArtifactPredicateFactory())); + return result; + } + + private RepositoryLayoutProvider repositoryLayoutProvider; + + public final RepositoryLayoutProvider getRepositoryLayoutProvider() { + checkClosed(); + if (repositoryLayoutProvider == null) { + repositoryLayoutProvider = createRepositoryLayoutProvider(); + } + return repositoryLayoutProvider; + } + + protected RepositoryLayoutProvider createRepositoryLayoutProvider() { + return new DefaultRepositoryLayoutProvider(getRepositoryLayoutFactories()); + } + + private LocalRepositoryProvider localRepositoryProvider; + + public final LocalRepositoryProvider getLocalRepositoryProvider() { + checkClosed(); + if (localRepositoryProvider == null) { + localRepositoryProvider = createLocalRepositoryProvider(); + } + return localRepositoryProvider; + } + + protected LocalRepositoryProvider createLocalRepositoryProvider() { + LocalPathComposer localPathComposer = getLocalPathComposer(); + HashMap localRepositoryProviders = new HashMap<>(2); + localRepositoryProviders.put( + SimpleLocalRepositoryManagerFactory.NAME, new SimpleLocalRepositoryManagerFactory(localPathComposer)); + localRepositoryProviders.put( + EnhancedLocalRepositoryManagerFactory.NAME, + new EnhancedLocalRepositoryManagerFactory( + localPathComposer, getTrackingFileManager(), getLocalPathPrefixComposerFactory())); + return new DefaultLocalRepositoryProvider(localRepositoryProviders); + } + + private RemoteRepositoryManager remoteRepositoryManager; + + public final RemoteRepositoryManager getRemoteRepositoryManager() { + checkClosed(); + if (remoteRepositoryManager == null) { + remoteRepositoryManager = createRemoteRepositoryManager(); + } + return remoteRepositoryManager; + } + + protected RemoteRepositoryManager createRemoteRepositoryManager() { + return new DefaultRemoteRepositoryManager(getUpdatePolicyAnalyzer(), getChecksumPolicyProvider()); + } + + private Map remoteRepositoryFilterSources; + + public final Map getRemoteRepositoryFilterSources() { + checkClosed(); + if (remoteRepositoryFilterSources == null) { + remoteRepositoryFilterSources = createRemoteRepositoryFilterSources(); + } + return remoteRepositoryFilterSources; + } + + protected Map createRemoteRepositoryFilterSources() { + HashMap result = new HashMap<>(); + result.put( + GroupIdRemoteRepositoryFilterSource.NAME, + new GroupIdRemoteRepositoryFilterSource(getRepositorySystemLifecycle())); + result.put( + PrefixesRemoteRepositoryFilterSource.NAME, + new PrefixesRemoteRepositoryFilterSource(getRepositoryLayoutProvider())); + return result; + } + + private RemoteRepositoryFilterManager remoteRepositoryFilterManager; + + public final RemoteRepositoryFilterManager getRemoteRepositoryFilterManager() { + checkClosed(); + if (remoteRepositoryFilterManager == null) { + remoteRepositoryFilterManager = createRemoteRepositoryFilterManager(); + } + return remoteRepositoryFilterManager; + } + + protected RemoteRepositoryFilterManager createRemoteRepositoryFilterManager() { + return new DefaultRemoteRepositoryFilterManager(getRemoteRepositoryFilterSources()); + } + + private Map repositoryListeners; + + public final Map getRepositoryListeners() { + checkClosed(); + if (repositoryListeners == null) { + repositoryListeners = createRepositoryListeners(); + } + return repositoryListeners; + } + + protected Map createRepositoryListeners() { + return new HashMap<>(); + } + + private RepositoryEventDispatcher repositoryEventDispatcher; + + public final RepositoryEventDispatcher getRepositoryEventDispatcher() { + checkClosed(); + if (repositoryEventDispatcher == null) { + repositoryEventDispatcher = createRepositoryEventDispatcher(); + } + return repositoryEventDispatcher; + } + + protected RepositoryEventDispatcher createRepositoryEventDispatcher() { + return new DefaultRepositoryEventDispatcher(getRepositoryListeners()); + } + + private Map trustedChecksumsSources; + + public final Map getTrustedChecksumsSources() { + checkClosed(); + if (trustedChecksumsSources == null) { + trustedChecksumsSources = createTrustedChecksumsSources(); + } + return trustedChecksumsSources; + } + + protected Map createTrustedChecksumsSources() { + HashMap result = new HashMap<>(); + result.put( + SparseDirectoryTrustedChecksumsSource.NAME, + new SparseDirectoryTrustedChecksumsSource(getChecksumProcessor(), getLocalPathComposer())); + result.put( + SummaryFileTrustedChecksumsSource.NAME, + new SummaryFileTrustedChecksumsSource(getLocalPathComposer(), getRepositorySystemLifecycle())); + return result; + } + + private Map providedChecksumsSources; + + public final Map getProvidedChecksumsSources() { + checkClosed(); + if (providedChecksumsSources == null) { + providedChecksumsSources = createProvidedChecksumsSources(); + } + return providedChecksumsSources; + } + + protected Map createProvidedChecksumsSources() { + HashMap result = new HashMap<>(); + result.put( + TrustedToProvidedChecksumsSourceAdapter.NAME, + new TrustedToProvidedChecksumsSourceAdapter(getTrustedChecksumsSources())); + return result; + } + + private Map checksumExtractorStrategies; + + public final Map getChecksumExtractorStrategies() { + checkClosed(); + if (checksumExtractorStrategies == null) { + checksumExtractorStrategies = createChecksumExtractorStrategies(); + } + return checksumExtractorStrategies; + } + + protected Map createChecksumExtractorStrategies() { + HashMap result = new HashMap<>(); + result.put(XChecksumExtractor.NAME, new XChecksumExtractor()); + result.put(Nx2ChecksumExtractor.NAME, new Nx2ChecksumExtractor()); + return result; + } + + private ChecksumExtractor checksumExtractor; + + public final ChecksumExtractor getChecksumExtractor() { + checkClosed(); + if (checksumExtractor == null) { + checksumExtractor = createChecksumExtractor(); + } + return checksumExtractor; + } + + protected ChecksumExtractor createChecksumExtractor() { + return new DefaultChecksumExtractor(getChecksumExtractorStrategies()); + } + + private Map transporterFactories; + + public final Map getTransporterFactories() { + checkClosed(); + if (transporterFactories == null) { + transporterFactories = createTransporterFactories(); + } + return transporterFactories; + } + + protected Map createTransporterFactories() { + HashMap result = new HashMap<>(); + result.put(FileTransporterFactory.NAME, new FileTransporterFactory()); + result.put( + ApacheTransporterFactory.NAME, + new ApacheTransporterFactory(getChecksumExtractor(), getPathProcessor())); + return result; + } + + private TransporterProvider transporterProvider; + + public final TransporterProvider getTransporterProvider() { + checkClosed(); + if (transporterProvider == null) { + transporterProvider = createTransporterProvider(); + } + return transporterProvider; + } + + protected TransporterProvider createTransporterProvider() { + return new DefaultTransporterProvider(getTransporterFactories()); + } + + private BasicRepositoryConnectorFactory basicRepositoryConnectorFactory; + + public final BasicRepositoryConnectorFactory getBasicRepositoryConnectorFactory() { + checkClosed(); + if (basicRepositoryConnectorFactory == null) { + basicRepositoryConnectorFactory = createBasicRepositoryConnectorFactory(); + } + return basicRepositoryConnectorFactory; + } + + protected BasicRepositoryConnectorFactory createBasicRepositoryConnectorFactory() { + return new BasicRepositoryConnectorFactory( + getTransporterProvider(), + getRepositoryLayoutProvider(), + getChecksumPolicyProvider(), + getChecksumProcessor(), + getProvidedChecksumsSources()); + } + + private Map repositoryConnectorFactories; + + public final Map getRepositoryConnectorFactories() { + checkClosed(); + if (repositoryConnectorFactories == null) { + repositoryConnectorFactories = createRepositoryConnectorFactories(); + } + return repositoryConnectorFactories; + } + + protected Map createRepositoryConnectorFactories() { + HashMap result = new HashMap<>(); + result.put(BasicRepositoryConnectorFactory.NAME, getBasicRepositoryConnectorFactory()); + return result; + } + + private RepositoryConnectorProvider repositoryConnectorProvider; + + public final RepositoryConnectorProvider getRepositoryConnectorProvider() { + checkClosed(); + if (repositoryConnectorProvider == null) { + repositoryConnectorProvider = createRepositoryConnectorProvider(); + } + return repositoryConnectorProvider; + } + + protected RepositoryConnectorProvider createRepositoryConnectorProvider() { + return new DefaultRepositoryConnectorProvider( + getRepositoryConnectorFactories(), getRemoteRepositoryFilterManager()); + } + + private Installer installer; + + public final Installer getInstaller() { + checkClosed(); + if (installer == null) { + installer = createInstaller(); + } + return installer; + } + + protected Installer createInstaller() { + return new DefaultInstaller( + getPathProcessor(), + getRepositoryEventDispatcher(), + getArtifactGeneratorFactories(), + getMetadataGeneratorFactories(), + getSyncContextFactory()); + } + + private Deployer deployer; + + public final Deployer getDeployer() { + checkClosed(); + if (deployer == null) { + deployer = createDeployer(); + } + return deployer; + } + + protected Deployer createDeployer() { + return new DefaultDeployer( + getPathProcessor(), + getRepositoryEventDispatcher(), + getRepositoryConnectorProvider(), + getRemoteRepositoryManager(), + getUpdateCheckManager(), + getArtifactGeneratorFactories(), + getMetadataGeneratorFactories(), + getSyncContextFactory(), + getOfflineController()); + } + + private Map dependencyCollectorDelegates; + + public final Map getDependencyCollectorDelegates() { + checkClosed(); + if (dependencyCollectorDelegates == null) { + dependencyCollectorDelegates = createDependencyCollectorDelegates(); + } + return dependencyCollectorDelegates; + } + + protected Map createDependencyCollectorDelegates() { + RemoteRepositoryManager remoteRepositoryManager = getRemoteRepositoryManager(); + ArtifactDescriptorReader artifactDescriptorReader = getArtifactDescriptorReader(); + VersionRangeResolver versionRangeResolver = getVersionRangeResolver(); + HashMap result = new HashMap<>(); + result.put( + DfDependencyCollector.NAME, + new DfDependencyCollector( + remoteRepositoryManager, + artifactDescriptorReader, + versionRangeResolver, + getArtifactDecoratorFactories())); + result.put( + BfDependencyCollector.NAME, + new BfDependencyCollector( + remoteRepositoryManager, + artifactDescriptorReader, + versionRangeResolver, + getArtifactDecoratorFactories())); + return result; + } + + private DependencyCollector dependencyCollector; + + public final DependencyCollector getDependencyCollector() { + checkClosed(); + if (dependencyCollector == null) { + dependencyCollector = createDependencyCollector(); + } + return dependencyCollector; + } + + protected DependencyCollector createDependencyCollector() { + return new DefaultDependencyCollector(getDependencyCollectorDelegates()); + } + + private Map artifactResolverPostProcessors; + + public final Map getArtifactResolverPostProcessors() { + checkClosed(); + if (artifactResolverPostProcessors == null) { + artifactResolverPostProcessors = createArtifactResolverPostProcessors(); + } + return artifactResolverPostProcessors; + } + + protected Map createArtifactResolverPostProcessors() { + HashMap result = new HashMap<>(); + result.put( + TrustedChecksumsArtifactResolverPostProcessor.NAME, + new TrustedChecksumsArtifactResolverPostProcessor( + getChecksumAlgorithmFactorySelector(), getTrustedChecksumsSources())); + return result; + } + + private ArtifactResolver artifactResolver; + + public final ArtifactResolver getArtifactResolver() { + checkClosed(); + if (artifactResolver == null) { + artifactResolver = createArtifactResolver(); + } + return artifactResolver; + } + + protected ArtifactResolver createArtifactResolver() { + return new DefaultArtifactResolver( + getPathProcessor(), + getRepositoryEventDispatcher(), + getVersionResolver(), + getUpdateCheckManager(), + getRepositoryConnectorProvider(), + getRemoteRepositoryManager(), + getSyncContextFactory(), + getOfflineController(), + getArtifactResolverPostProcessors(), + getRemoteRepositoryFilterManager()); + } + + private MetadataResolver metadataResolver; + + public final MetadataResolver getMetadataResolver() { + checkClosed(); + if (metadataResolver == null) { + metadataResolver = createMetadataResolver(); + } + return metadataResolver; + } + + protected MetadataResolver createMetadataResolver() { + return new DefaultMetadataResolver( + getRepositoryEventDispatcher(), + getUpdateCheckManager(), + getRepositoryConnectorProvider(), + getRemoteRepositoryManager(), + getSyncContextFactory(), + getOfflineController(), + getRemoteRepositoryFilterManager(), + getPathProcessor()); + } + + private VersionScheme versionScheme; + + public final VersionScheme getVersionScheme() { + checkClosed(); + if (versionScheme == null) { + versionScheme = createVersionScheme(); + } + return versionScheme; + } + + protected VersionScheme createVersionScheme() { + return new GenericVersionScheme(); + } + + private Map artifactGeneratorFactories; + + public final Map getArtifactGeneratorFactories() { + checkClosed(); + if (artifactGeneratorFactories == null) { + artifactGeneratorFactories = createArtifactGeneratorFactories(); + } + return artifactGeneratorFactories; + } + + protected Map createArtifactGeneratorFactories() { + // by default none, this is extension point + return new HashMap<>(); + } + + private Map artifactDecoratorFactories; + + public final Map getArtifactDecoratorFactories() { + checkClosed(); + if (artifactDecoratorFactories == null) { + artifactDecoratorFactories = createArtifactDecoratorFactories(); + } + return artifactDecoratorFactories; + } + + protected Map createArtifactDecoratorFactories() { + // by default none, this is extension point + return new HashMap<>(); + } + + // Maven provided + + private Map metadataGeneratorFactories; + + public final Map getMetadataGeneratorFactories() { + checkClosed(); + if (metadataGeneratorFactories == null) { + metadataGeneratorFactories = createMetadataGeneratorFactories(); + } + return metadataGeneratorFactories; + } + + protected Map createMetadataGeneratorFactories() { + // from maven-resolver-provider + HashMap result = new HashMap<>(); + result.put(PluginsMetadataGeneratorFactory.NAME, new PluginsMetadataGeneratorFactory()); + result.put(VersionsMetadataGeneratorFactory.NAME, new VersionsMetadataGeneratorFactory()); + result.put(SnapshotMetadataGeneratorFactory.NAME, new SnapshotMetadataGeneratorFactory()); + return result; + } + + private LinkedHashMap artifactRelocationSources; + + public final LinkedHashMap getMavenArtifactRelocationSources() { + checkClosed(); + if (artifactRelocationSources == null) { + artifactRelocationSources = createMavenArtifactRelocationSources(); + } + return artifactRelocationSources; + } + + protected LinkedHashMap createMavenArtifactRelocationSources() { + // from maven-resolver-provider + LinkedHashMap result = new LinkedHashMap<>(); + result.put(UserPropertiesArtifactRelocationSource.NAME, new UserPropertiesArtifactRelocationSource()); + result.put( + DistributionManagementArtifactRelocationSource.NAME, + new DistributionManagementArtifactRelocationSource()); + return result; + } + + private ArtifactDescriptorReader artifactDescriptorReader; + + public final ArtifactDescriptorReader getArtifactDescriptorReader() { + checkClosed(); + if (artifactDescriptorReader == null) { + artifactDescriptorReader = createArtifactDescriptorReader(); + } + return artifactDescriptorReader; + } + + protected ArtifactDescriptorReader createArtifactDescriptorReader() { + // from maven-resolver-provider + return new DefaultArtifactDescriptorReader( + getRemoteRepositoryManager(), + getVersionResolver(), + getVersionRangeResolver(), + getArtifactResolver(), + getModelBuilder(), + getRepositoryEventDispatcher(), + getMavenArtifactRelocationSources()); + } + + private VersionResolver versionResolver; + + public final VersionResolver getVersionResolver() { + checkClosed(); + if (versionResolver == null) { + versionResolver = createVersionResolver(); + } + return versionResolver; + } + + protected VersionResolver createVersionResolver() { + // from maven-resolver-provider + return new DefaultVersionResolver( + getMetadataResolver(), getSyncContextFactory(), getRepositoryEventDispatcher()); + } + + private VersionRangeResolver versionRangeResolver; + + public final VersionRangeResolver getVersionRangeResolver() { + checkClosed(); + if (versionRangeResolver == null) { + versionRangeResolver = createVersionRangeResolver(); + } + return versionRangeResolver; + } + + protected VersionRangeResolver createVersionRangeResolver() { + // from maven-resolver-provider + return new DefaultVersionRangeResolver( + getMetadataResolver(), getSyncContextFactory(), getRepositoryEventDispatcher(), getVersionScheme()); + } + + private ModelBuilder modelBuilder; + + public final ModelBuilder getModelBuilder() { + checkClosed(); + if (modelBuilder == null) { + modelBuilder = createModelBuilder(); + } + return modelBuilder; + } + + protected ModelBuilder createModelBuilder() { + // from maven-model-builder + DefaultModelProcessor modelProcessor = new DefaultModelProcessor(new DefaultModelXmlFactory(), List.of()); + return new DefaultModelBuilder( + modelProcessor, + new DefaultModelValidator(new DefaultModelVersionProcessor()), + new DefaultModelNormalizer(), + new DefaultModelInterpolator( + new DefaultPathTranslator(), new DefaultUrlNormalizer(), new DefaultRootLocator()), + new DefaultModelPathTranslator(new DefaultPathTranslator()), + new DefaultModelUrlNormalizer(new DefaultUrlNormalizer()), + new DefaultSuperPomProvider(modelProcessor), + new DefaultInheritanceAssembler(), + new DefaultProfileSelector(), + new DefaultProfileInjector(), + new DefaultPluginManagementInjector(), + new DefaultDependencyManagementInjector(), + new DefaultDependencyManagementImporter(), + (m, r, b) -> m, + new DefaultPluginConfigurationExpander(), + new ProfileActivationFilePathInterpolator(new DefaultPathTranslator(), new DefaultRootLocator()), + new BuildModelTransformer(), + new DefaultModelVersionParser(getVersionScheme())); + } + + private RepositorySystem repositorySystem; + + public final RepositorySystem getRepositorySystem() { + checkClosed(); + if (repositorySystem == null) { + repositorySystem = createRepositorySystem(); + } + return repositorySystem; + } + + protected RepositorySystem createRepositorySystem() { + return new DefaultRepositorySystem( + getVersionResolver(), + getVersionRangeResolver(), + getArtifactResolver(), + getMetadataResolver(), + getArtifactDescriptorReader(), + getDependencyCollector(), + getInstaller(), + getDeployer(), + getLocalRepositoryProvider(), + getSyncContextFactory(), + getRemoteRepositoryManager(), + getRepositorySystemLifecycle(), + getArtifactDecoratorFactories()); + } + + @Override + public RepositorySystem get() { + return getRepositorySystem(); + } +} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionMock.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionMock.java new file mode 100644 index 0000000..c620b13 --- /dev/null +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionMock.java @@ -0,0 +1,393 @@ +/* + * 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.plugin.testing.stubs; + +import java.net.URI; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +import org.apache.maven.api.Artifact; +import org.apache.maven.api.LocalRepository; +import org.apache.maven.api.Project; +import org.apache.maven.api.RemoteRepository; +import org.apache.maven.api.Session; +import org.apache.maven.api.SessionData; +import org.apache.maven.api.model.Model; +import org.apache.maven.api.model.Repository; +import org.apache.maven.api.services.ArtifactDeployer; +import org.apache.maven.api.services.ArtifactDeployerRequest; +import org.apache.maven.api.services.ArtifactFactory; +import org.apache.maven.api.services.ArtifactFactoryRequest; +import org.apache.maven.api.services.ArtifactInstaller; +import org.apache.maven.api.services.ArtifactInstallerRequest; +import org.apache.maven.api.services.ArtifactManager; +import org.apache.maven.api.services.LocalRepositoryManager; +import org.apache.maven.api.services.ProjectBuilder; +import org.apache.maven.api.services.ProjectBuilderRequest; +import org.apache.maven.api.services.ProjectBuilderResult; +import org.apache.maven.api.services.ProjectManager; +import org.apache.maven.api.services.RepositoryFactory; +import org.apache.maven.api.services.VersionParser; +import org.apache.maven.api.services.xml.ModelXmlFactory; +import org.apache.maven.internal.impl.DefaultModelXmlFactory; +import org.apache.maven.internal.impl.DefaultVersionParser; +import org.apache.maven.internal.impl.InternalSession; +import org.apache.maven.model.v4.MavenStaxReader; +import org.apache.maven.repository.internal.DefaultModelVersionParser; +import org.eclipse.aether.util.version.GenericVersionScheme; +import org.mockito.ArgumentMatchers; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +/** + * + */ +public class SessionMock { + + public static InternalSession getMockSession(String localRepo) { + LocalRepository localRepository = mock(LocalRepository.class); + when(localRepository.getId()).thenReturn("local"); + when(localRepository.getPath()).thenReturn(Paths.get(localRepo)); + return getMockSession(localRepository); + } + + public static InternalSession getMockSession(LocalRepository localRepository) { + InternalSession session = mock(InternalSession.class); + + // + // RepositoryFactory + // + RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); + when(session.createRemoteRepository(anyString(), anyString())).thenAnswer(iom -> { + String id = iom.getArgument(0, String.class); + String url = iom.getArgument(1, String.class); + return session.getService(RepositoryFactory.class).createRemote(id, url); + }); + when(session.createRemoteRepository(any())) + .thenAnswer(iom -> repositoryFactory.createRemote(iom.getArgument(0, Repository.class))); + when(repositoryFactory.createRemote(any(Repository.class))).thenAnswer(iom -> { + Repository repository = iom.getArgument(0, Repository.class); + return repositoryFactory.createRemote(repository.getId(), repository.getUrl()); + }); + when(repositoryFactory.createRemote(anyString(), anyString())).thenAnswer(iom -> { + String id = iom.getArgument(0, String.class); + String url = iom.getArgument(1, String.class); + RemoteRepository remoteRepository = + mock(RemoteRepository.class, withSettings().lenient()); + when(remoteRepository.getId()).thenReturn(id); + when(remoteRepository.getUrl()).thenReturn(url); + when(remoteRepository.getProtocol()).thenReturn(URI.create(url).getScheme()); + return remoteRepository; + }); + when(session.getService(RepositoryFactory.class)).thenReturn(repositoryFactory); + + // + // VersionParser + // + VersionParser versionParser = + new DefaultVersionParser(new DefaultModelVersionParser(new GenericVersionScheme())); + when(session.parseVersion(any())) + .thenAnswer(iom -> versionParser.parseVersion(iom.getArgument(0, String.class))); + when(session.getService(VersionParser.class)).thenReturn(versionParser); + + // + // LocalRepositoryManager + // + LocalRepositoryManager localRepositoryManager = mock(LocalRepositoryManager.class); + when(session.getPathForLocalArtifact(any(Artifact.class))) + .then(iom -> localRepositoryManager.getPathForLocalArtifact( + session, session.getLocalRepository(), iom.getArgument(0, Artifact.class))); + when(session.getPathForRemoteArtifact(any(), any())) + .thenAnswer(iom -> localRepositoryManager.getPathForRemoteArtifact( + session, + session.getLocalRepository(), + iom.getArgument(0, RemoteRepository.class), + iom.getArgument(1, Artifact.class))); + when(localRepositoryManager.getPathForLocalArtifact(any(), any(), any())) + .thenAnswer(iom -> { + LocalRepository localRepo = iom.getArgument(1, LocalRepository.class); + Artifact artifact = iom.getArgument(2, Artifact.class); + return localRepo.getPath().resolve(getPathForArtifact(artifact, true)); + }); + when(session.getService(LocalRepositoryManager.class)).thenReturn(localRepositoryManager); + + // + // ArtifactInstaller + // + ArtifactInstaller artifactInstaller = mock(ArtifactInstaller.class); + doAnswer(iom -> { + artifactInstaller.install( + ArtifactInstallerRequest.build(session, iom.getArgument(0, Collection.class))); + return null; + }) + .when(session) + .installArtifacts(any(Collection.class)); + doAnswer(iom -> { + artifactInstaller.install(ArtifactInstallerRequest.build( + session, Arrays.asList(iom.getArgument(0, Artifact[].class)))); + return null; + }) + .when(session) + .installArtifacts(any(Artifact[].class)); + doAnswer(iom -> { + artifactInstaller.install(ArtifactInstallerRequest.build( + iom.getArgument(0, Session.class), iom.getArgument(1, Collection.class))); + return null; + }) + .when(artifactInstaller) + .install(any(Session.class), ArgumentMatchers.>any()); + when(session.getService(ArtifactInstaller.class)).thenReturn(artifactInstaller); + + // + // ArtifactDeployer + // + ArtifactDeployer artifactDeployer = mock(ArtifactDeployer.class); + doAnswer(iom -> { + artifactDeployer.deploy(ArtifactDeployerRequest.build( + iom.getArgument(0, Session.class), + iom.getArgument(1, RemoteRepository.class), + Arrays.asList(iom.getArgument(2, Artifact[].class)))); + return null; + }) + .when(session) + .deployArtifact(any(), any()); + doAnswer(iom -> { + artifactDeployer.deploy(ArtifactDeployerRequest.build( + iom.getArgument(0, Session.class), + iom.getArgument(1, RemoteRepository.class), + iom.getArgument(2, Collection.class))); + return null; + }) + .when(artifactDeployer) + .deploy(any(), any(), any()); + when(session.getService(ArtifactDeployer.class)).thenReturn(artifactDeployer); + + // + // ArtifactManager + // + ArtifactManager artifactManager = mock(ArtifactManager.class); + Map paths = new HashMap<>(); + doAnswer(iom -> { + paths.put(iom.getArgument(0), iom.getArgument(1)); + return null; + }) + .when(artifactManager) + .setPath(any(), any()); + doAnswer(iom -> Optional.ofNullable(paths.get(iom.getArgument(0, Artifact.class)))) + .when(artifactManager) + .getPath(any()); + doAnswer(iom -> artifactManager.getPath(iom.getArgument(0, Artifact.class))) + .when(session) + .getArtifactPath(any()); + when(session.getService(ArtifactManager.class)).thenReturn(artifactManager); + + // + // ProjectManager + // + ProjectManager projectManager = mock(ProjectManager.class); + Map> attachedArtifacts = new HashMap<>(); + doAnswer(iom -> { + Project project = iom.getArgument(1, Project.class); + String type = iom.getArgument(2, String.class); + Path path = iom.getArgument(3, Path.class); + Artifact artifact = session.createArtifact( + project.getGroupId(), project.getArtifactId(), project.getVersion(), null, null, type); + artifactManager.setPath(artifact, path); + attachedArtifacts + .computeIfAbsent(project, p -> new ArrayList<>()) + .add(artifact); + return null; + }) + .when(projectManager) + .attachArtifact(same(session), any(Project.class), any(), any()); + doAnswer(iom -> { + Project project = iom.getArgument(0, Project.class); + Artifact artifact = iom.getArgument(1, Artifact.class); + Path path = iom.getArgument(2, Path.class); + artifactManager.setPath(artifact, path); + attachedArtifacts + .computeIfAbsent(project, p -> new ArrayList<>()) + .add(artifact); + return null; + }) + .when(projectManager) + .attachArtifact(any(Project.class), any(Artifact.class), any(Path.class)); + when(projectManager.getAttachedArtifacts(any())) + .then(iom -> + attachedArtifacts.computeIfAbsent(iom.getArgument(0, Project.class), p -> new ArrayList<>())); + when(projectManager.getAllArtifacts(any())).then(iom -> { + Project project = iom.getArgument(0, Project.class); + List result = new ArrayList<>(); + result.addAll(project.getArtifacts()); + result.addAll(attachedArtifacts.computeIfAbsent(project, p -> new ArrayList<>())); + return result; + }); + when(session.getService(ProjectManager.class)).thenReturn(projectManager); + + // + // ArtifactFactory + // + ArtifactFactory artifactFactory = mock(ArtifactFactory.class); + when(artifactFactory.create(any())).then(iom -> { + ArtifactFactoryRequest request = iom.getArgument(0, ArtifactFactoryRequest.class); + String classifier = request.getClassifier(); + String extension = request.getExtension(); + String type = request.getType(); + if (classifier == null) { + classifier = ""; + } + if (extension == null) { + extension = type != null ? type : ""; + } + return new ArtifactStub( + request.getGroupId(), request.getArtifactId(), classifier, request.getVersion(), extension); + }); + when(session.createArtifact(any(), any(), any(), any(), any(), any())).thenAnswer(iom -> { + String groupId = iom.getArgument(0, String.class); + String artifactId = iom.getArgument(1, String.class); + String version = iom.getArgument(2, String.class); + String classifier = iom.getArgument(3, String.class); + String extension = iom.getArgument(4, String.class); + String type = iom.getArgument(5, String.class); + return session.getService(ArtifactFactory.class) + .create(ArtifactFactoryRequest.builder() + .session(session) + .groupId(groupId) + .artifactId(artifactId) + .version(version) + .classifier(classifier) + .extension(extension) + .type(type) + .build()); + }); + when(session.createArtifact(any(), any(), any(), any())).thenAnswer(iom -> { + String groupId = iom.getArgument(0, String.class); + String artifactId = iom.getArgument(1, String.class); + String version = iom.getArgument(2, String.class); + String extension = iom.getArgument(3, String.class); + return session.getService(ArtifactFactory.class) + .create(ArtifactFactoryRequest.builder() + .session(session) + .groupId(groupId) + .artifactId(artifactId) + .version(version) + .extension(extension) + .build()); + }); + when(session.getService(ArtifactFactory.class)).thenReturn(artifactFactory); + + // + // ProjectBuilder + // + ProjectBuilder projectBuilder = mock(ProjectBuilder.class); + when(projectBuilder.build(any(ProjectBuilderRequest.class))).then(iom -> { + ProjectBuilderRequest request = iom.getArgument(0, ProjectBuilderRequest.class); + ProjectBuilderResult result = mock(ProjectBuilderResult.class); + Model model = new MavenStaxReader().read(request.getSource().get().openStream()); + ProjectStub projectStub = new ProjectStub(); + projectStub.setModel(model); + ArtifactStub artifactStub = new ArtifactStub( + model.getGroupId(), model.getArtifactId(), "", model.getVersion(), model.getPackaging()); + if (!"pom".equals(model.getPackaging())) { + projectStub.setMainArtifact(artifactStub); + } + when(result.getProject()).thenReturn(Optional.of(projectStub)); + return result; + }); + when(session.getService(ProjectBuilder.class)).thenReturn(projectBuilder); + + // + // ModelXmlFactory + // + when(session.getService(ModelXmlFactory.class)).thenReturn(new DefaultModelXmlFactory()); + + // + // Other + // + Properties sysProps = new Properties(); + Properties usrProps = new Properties(); + doReturn(sysProps).when(session).getSystemProperties(); + doReturn(usrProps).when(session).getUserProperties(); + when(session.getLocalRepository()).thenReturn(localRepository); + when(session.getData()).thenReturn(new TestSessionData()); + when(session.withLocalRepository(any())) + .thenAnswer(iom -> getMockSession(iom.getArgument(0, LocalRepository.class))); + + return session; + } + + static String getPathForArtifact(Artifact artifact, boolean local) { + StringBuilder path = new StringBuilder(128); + path.append(artifact.getGroupId().replace('.', '/')).append('/'); + path.append(artifact.getArtifactId()).append('/'); + path.append(artifact.getVersion()).append('/'); + path.append(artifact.getArtifactId()).append('-'); + path.append(artifact.getVersion()); + if (artifact.getClassifier().length() > 0) { + path.append('-').append(artifact.getClassifier()); + } + if (artifact.getExtension().length() > 0) { + path.append('.').append(artifact.getExtension()); + } + return path.toString(); + } + + static class TestSessionData implements SessionData { + private final Map, Object> map = new ConcurrentHashMap<>(); + + @Override + public void set(Key key, T value) { + map.put(key, value); + } + + @Override + public boolean replace(Key key, T oldValue, T newValue) { + return map.replace(key, oldValue, newValue); + } + + @Override + @SuppressWarnings("unchecked") + public T get(Key key) { + return (T) map.get(key); + } + + @Override + @SuppressWarnings("unchecked") + public T computeIfAbsent(Key key, Supplier supplier) { + return (T) map.computeIfAbsent(key, k -> supplier.get()); + } + } +} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionStub.java index 2b05567..34b1820 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionStub.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionStub.java @@ -18,261 +18,393 @@ */ package org.apache.maven.api.plugin.testing.stubs; -import java.net.URI; import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; +import java.time.Instant; import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Properties; import org.apache.maven.api.Artifact; +import org.apache.maven.api.ArtifactCoordinate; +import org.apache.maven.api.Dependency; +import org.apache.maven.api.DependencyCoordinate; +import org.apache.maven.api.DependencyScope; +import org.apache.maven.api.Language; +import org.apache.maven.api.Listener; import org.apache.maven.api.LocalRepository; +import org.apache.maven.api.Node; +import org.apache.maven.api.Packaging; +import org.apache.maven.api.PathScope; +import org.apache.maven.api.PathType; import org.apache.maven.api.Project; +import org.apache.maven.api.ProjectScope; import org.apache.maven.api.RemoteRepository; +import org.apache.maven.api.Service; import org.apache.maven.api.Session; -import org.apache.maven.api.model.Model; +import org.apache.maven.api.SessionData; +import org.apache.maven.api.Type; +import org.apache.maven.api.Version; +import org.apache.maven.api.VersionConstraint; +import org.apache.maven.api.VersionRange; +import org.apache.maven.api.annotations.Nonnull; +import org.apache.maven.api.annotations.Nullable; import org.apache.maven.api.model.Repository; -import org.apache.maven.api.services.ArtifactDeployer; -import org.apache.maven.api.services.ArtifactDeployerRequest; -import org.apache.maven.api.services.ArtifactFactory; -import org.apache.maven.api.services.ArtifactFactoryRequest; -import org.apache.maven.api.services.ArtifactInstaller; -import org.apache.maven.api.services.ArtifactInstallerRequest; -import org.apache.maven.api.services.ArtifactManager; -import org.apache.maven.api.services.LocalRepositoryManager; -import org.apache.maven.api.services.ProjectBuilder; -import org.apache.maven.api.services.ProjectBuilderRequest; -import org.apache.maven.api.services.ProjectBuilderResult; -import org.apache.maven.api.services.ProjectManager; -import org.apache.maven.api.services.RepositoryFactory; -import org.apache.maven.api.services.xml.ModelXmlFactory; -import org.apache.maven.internal.impl.DefaultModelXmlFactory; -import org.apache.maven.model.v4.MavenStaxReader; -import org.mockito.ArgumentMatchers; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; +import org.apache.maven.api.settings.Settings; /** - * */ -public class SessionStub { - - public static Session getMockSession(String localRepo) { - LocalRepository localRepository = mock(LocalRepository.class); - when(localRepository.getId()).thenReturn("local"); - when(localRepository.getPath()).thenReturn(Paths.get(localRepo)); - return getMockSession(localRepository); - } - - public static Session getMockSession(LocalRepository localRepository) { - Session session = mock(Session.class); - - RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); - when(repositoryFactory.createRemote(any(Repository.class))).thenAnswer(iom -> { - Repository repository = iom.getArgument(0, Repository.class); - return repositoryFactory.createRemote(repository.getId(), repository.getUrl()); - }); - when(repositoryFactory.createRemote(anyString(), anyString())).thenAnswer(iom -> { - String id = iom.getArgument(0, String.class); - String url = iom.getArgument(1, String.class); - RemoteRepository remoteRepository = - mock(RemoteRepository.class, withSettings().lenient()); - when(remoteRepository.getId()).thenReturn(id); - when(remoteRepository.getUrl()).thenReturn(url); - when(remoteRepository.getProtocol()).thenReturn(URI.create(url).getScheme()); - return remoteRepository; - }); - - LocalRepositoryManager localRepositoryManager = mock(LocalRepositoryManager.class); - when(localRepositoryManager.getPathForLocalArtifact(any(), any(), any())) - .thenAnswer(iom -> { - LocalRepository localRepo = iom.getArgument(1, LocalRepository.class); - Artifact artifact = iom.getArgument(2, Artifact.class); - return localRepo.getPath().resolve(getPathForArtifact(artifact, true)); - }); - - ArtifactInstaller artifactInstaller = mock(ArtifactInstaller.class); - doAnswer(iom -> { - artifactInstaller.install(ArtifactInstallerRequest.build( - iom.getArgument(0, Session.class), iom.getArgument(1, Collection.class))); - return null; - }) - .when(artifactInstaller) - .install(any(Session.class), ArgumentMatchers.>any()); - - ArtifactDeployer artifactDeployer = mock(ArtifactDeployer.class); - doAnswer(iom -> { - artifactDeployer.deploy(ArtifactDeployerRequest.build( - iom.getArgument(0, Session.class), - iom.getArgument(1, RemoteRepository.class), - iom.getArgument(2, Collection.class))); - return null; - }) - .when(artifactDeployer) - .deploy(any(), any(), any()); - - ArtifactManager artifactManager = mock(ArtifactManager.class); - Map paths = new HashMap<>(); - doAnswer(iom -> { - paths.put(iom.getArgument(0), iom.getArgument(1)); - return null; - }) - .when(artifactManager) - .setPath(any(), any()); - doAnswer(iom -> Optional.ofNullable(paths.get(iom.getArgument(0, Artifact.class)))) - .when(artifactManager) - .getPath(any()); - - ProjectManager projectManager = mock(ProjectManager.class); - Map> attachedArtifacts = new HashMap<>(); - doAnswer(iom -> { - Project project = iom.getArgument(1, Project.class); - String type = iom.getArgument(2, String.class); - Path path = iom.getArgument(3, Path.class); - Artifact artifact = session.createArtifact( - project.getGroupId(), project.getArtifactId(), project.getVersion(), null, null, type); - artifactManager.setPath(artifact, path); - attachedArtifacts - .computeIfAbsent(project, p -> new ArrayList<>()) - .add(artifact); - return null; - }) - .when(projectManager) - .attachArtifact(same(session), any(Project.class), any(), any()); - doAnswer(iom -> { - Project project = iom.getArgument(0, Project.class); - Artifact artifact = iom.getArgument(1, Artifact.class); - Path path = iom.getArgument(2, Path.class); - artifactManager.setPath(artifact, path); - attachedArtifacts - .computeIfAbsent(project, p -> new ArrayList<>()) - .add(artifact); - return null; - }) - .when(projectManager) - .attachArtifact(any(Project.class), any(Artifact.class), any(Path.class)); - when(projectManager.getAttachedArtifacts(any())) - .then(iom -> - attachedArtifacts.computeIfAbsent(iom.getArgument(0, Project.class), p -> new ArrayList<>())); - - ArtifactFactory artifactFactory = mock(ArtifactFactory.class); - when(artifactFactory.create(any())).then(iom -> { - ArtifactFactoryRequest request = iom.getArgument(0, ArtifactFactoryRequest.class); - String classifier = request.getClassifier(); - String extension = request.getExtension(); - String type = request.getType(); - if (classifier == null) { - classifier = ""; - } - if (extension == null) { - extension = type != null ? type : ""; - } - return new ArtifactStub( - request.getGroupId(), request.getArtifactId(), classifier, request.getVersion(), extension); - }); - - ProjectBuilder projectBuilder = mock(ProjectBuilder.class); - when(projectBuilder.build(any(ProjectBuilderRequest.class))).then(iom -> { - ProjectBuilderRequest request = iom.getArgument(0, ProjectBuilderRequest.class); - ProjectBuilderResult result = mock(ProjectBuilderResult.class); - Model model = new MavenStaxReader().read(request.getSource().get().openStream()); - ProjectStub projectStub = new ProjectStub(); - projectStub.setModel(model); - ArtifactStub artifactStub = new ArtifactStub( - model.getGroupId(), model.getArtifactId(), "", model.getVersion(), model.getPackaging()); - projectStub.setArtifact(artifactStub); - when(result.getProject()).thenReturn(Optional.of(projectStub)); - return result; - }); - - Properties sysProps = new Properties(); - Properties usrProps = new Properties(); - doReturn(sysProps).when(session).getSystemProperties(); - doReturn(usrProps).when(session).getUserProperties(); - - when(session.getLocalRepository()).thenReturn(localRepository); - when(session.getService(RepositoryFactory.class)).thenReturn(repositoryFactory); - when(session.getService(ProjectBuilder.class)).thenReturn(projectBuilder); - when(session.getService(LocalRepositoryManager.class)).thenReturn(localRepositoryManager); - when(session.getService(ProjectManager.class)).thenReturn(projectManager); - when(session.getService(ArtifactManager.class)).thenReturn(artifactManager); - when(session.getService(ArtifactInstaller.class)).thenReturn(artifactInstaller); - when(session.getService(ArtifactDeployer.class)).thenReturn(artifactDeployer); - when(session.getService(ArtifactFactory.class)).thenReturn(artifactFactory); - when(session.getService(ModelXmlFactory.class)).thenReturn(new DefaultModelXmlFactory()); - - when(session.getPathForLocalArtifact(any(Artifact.class))) - .then(iom -> localRepositoryManager.getPathForLocalArtifact( - session, session.getLocalRepository(), iom.getArgument(0, Artifact.class))); - when(session.createArtifact(any(), any(), any(), any(), any(), any())).thenAnswer(iom -> { - String groupId = iom.getArgument(0, String.class); - String artifactId = iom.getArgument(1, String.class); - String version = iom.getArgument(2, String.class); - String classifier = iom.getArgument(3, String.class); - String extension = iom.getArgument(4, String.class); - String type = iom.getArgument(5, String.class); - return session.getService(ArtifactFactory.class) - .create(ArtifactFactoryRequest.builder() - .session(session) - .groupId(groupId) - .artifactId(artifactId) - .version(version) - .classifier(classifier) - .extension(extension) - .type(type) - .build()); - }); - when(session.createArtifact(any(), any(), any(), any())).thenAnswer(iom -> { - String groupId = iom.getArgument(0, String.class); - String artifactId = iom.getArgument(1, String.class); - String version = iom.getArgument(2, String.class); - String extension = iom.getArgument(3, String.class); - return session.getService(ArtifactFactory.class) - .create(ArtifactFactoryRequest.builder() - .session(session) - .groupId(groupId) - .artifactId(artifactId) - .version(version) - .extension(extension) - .build()); - }); - when(session.createRemoteRepository(anyString(), anyString())).thenAnswer(iom -> { - String id = iom.getArgument(0, String.class); - String url = iom.getArgument(1, String.class); - return session.getService(RepositoryFactory.class).createRemote(id, url); - }); - doAnswer(iom -> artifactManager.getPath(iom.getArgument(0, Artifact.class))) - .when(session) - .getArtifactPath(any()); - - when(session.withLocalRepository(any())) - .thenAnswer(iom -> getMockSession(iom.getArgument(0, LocalRepository.class))); - return session; - } - - static String getPathForArtifact(Artifact artifact, boolean local) { - StringBuilder path = new StringBuilder(128); - path.append(artifact.getGroupId().replace('.', '/')).append('/'); - path.append(artifact.getArtifactId()).append('/'); - path.append(artifact.getVersion()).append('/'); - path.append(artifact.getArtifactId()).append('-'); - path.append(artifact.getVersion()); - if (artifact.getClassifier().length() > 0) { - path.append('-').append(artifact.getClassifier()); +public class SessionStub implements Session { + + private Map userProperties; + + private Map systemProperties; + + private final Settings settings; + + public SessionStub(Settings settings) { + this(null, null, settings); + } + + public SessionStub() { + this(null, null, null); + } + + public SessionStub(Map userProperties) { + this(null, userProperties, null); + } + + public SessionStub(Map systemProperties, Map userProperties, Settings settings) { + + this.settings = settings; + + this.systemProperties = new HashMap<>(); + if (systemProperties != null) { + this.systemProperties.putAll(systemProperties); } - if (artifact.getExtension().length() > 0) { - path.append('.').append(artifact.getExtension()); + System.getProperties().forEach((k, v) -> this.systemProperties.put(k.toString(), v.toString())); + + this.userProperties = new HashMap<>(); + if (userProperties != null) { + this.userProperties.putAll(userProperties); } - return path.toString(); + } + + @Override + public Settings getSettings() { + return settings; + } + + @Override + public Map getSystemProperties() { + return this.systemProperties; + } + + @Override + public Map getUserProperties() { + return this.userProperties; + } + + @Nonnull + public Map getEffectiveProperties(@Nullable Project project) { + HashMap result = new HashMap<>(getSystemProperties()); + if (project != null) { + result.putAll(project.getModel().getProperties()); + } + result.putAll(getUserProperties()); + return result; + } + + @Override + public LocalRepository getLocalRepository() { + return null; + } + + @Override + public Path getTopDirectory() { + return null; + } + + @Override + public Path getRootDirectory() { + return null; + } + + @Override + public List getRemoteRepositories() { + return null; + } + + @Override + public SessionData getData() { + return null; + } + + @Override + public Version getMavenVersion() { + return null; + } + + @Override + public int getDegreeOfConcurrency() { + return 0; + } + + @Override + public Instant getStartTime() { + return null; + } + + @Override + public List getProjects() { + return null; + } + + @Override + public Map getPluginContext(Project project) { + return null; + } + + @Override + public T getService(Class clazz) { + return null; + } + + @Override + public Session withLocalRepository(LocalRepository localRepository) { + return null; + } + + @Override + public Session withRemoteRepositories(List repositories) { + return null; + } + + @Override + public void registerListener(Listener listener) {} + + @Override + public void unregisterListener(Listener listener) {} + + @Override + public Collection getListeners() { + return null; + } + + @Override + public LocalRepository createLocalRepository(Path path) { + return null; + } + + @Override + public RemoteRepository createRemoteRepository(String id, String url) { + return null; + } + + @Override + public RemoteRepository createRemoteRepository(Repository repository) { + return null; + } + + @Override + public Artifact createArtifact(String groupId, String artifactId, String version, String extension) { + return null; + } + + @Override + public Artifact createArtifact( + String groupId, String artifactId, String version, String classifier, String extension, String type) { + return null; + } + + @Override + public ArtifactCoordinate createArtifactCoordinate(String s, String s1, String s2, String s3) { + return null; + } + + @Override + public ArtifactCoordinate createArtifactCoordinate(String coordString) { + return null; + } + + @Override + public ArtifactCoordinate createArtifactCoordinate( + String s, String s1, String s2, String s3, String s4, String s5) { + return null; + } + + @Override + public ArtifactCoordinate createArtifactCoordinate(Artifact artifact) { + return null; + } + + @Override + public DependencyCoordinate createDependencyCoordinate(ArtifactCoordinate artifactCoordinate) { + return null; + } + + @Override + public DependencyCoordinate createDependencyCoordinate(Dependency dependency) { + return null; + } + + @Override + public Map.Entry resolveArtifact(Artifact artifact) { + return null; + } + + @Override + public Map.Entry resolveArtifact(ArtifactCoordinate coordinate) { + return null; + } + + @Override + public Map resolveArtifacts(ArtifactCoordinate... artifactCoordinates) { + return null; + } + + @Override + public Map resolveArtifacts(Collection collection) { + return null; + } + + @Override + public Map resolveArtifacts(Artifact... artifacts) { + return null; + } + + @Override + public List flattenDependencies(Node node, PathScope scope) { + return null; + } + + @Override + public List resolveDependencies(DependencyCoordinate dependencyCoordinate) { + return null; + } + + @Override + public List resolveDependencies(List dependencyCoordinates) { + return null; + } + + @Override + public List resolveDependencies(Project project, PathScope scope) { + return null; + } + + @Override + public Version resolveVersion(ArtifactCoordinate artifact) { + return null; + } + + @Override + public List resolveVersionRange(ArtifactCoordinate artifact) { + return null; + } + + @Override + public void installArtifacts(Artifact... artifacts) {} + + @Override + public void installArtifacts(Collection artifacts) {} + + @Override + public void deployArtifact(RemoteRepository repository, Artifact... artifacts) {} + + @Override + public void setArtifactPath(Artifact artifact, Path path) {} + + @Override + public Optional getArtifactPath(Artifact artifact) { + return Optional.empty(); + } + + @Override + public boolean isVersionSnapshot(String version) { + return false; + } + + @Override + public Node collectDependencies(Artifact artifact) { + return null; + } + + @Override + public Node collectDependencies(Project project) { + return null; + } + + @Override + public Node collectDependencies(DependencyCoordinate dependencyCoordinate) { + return null; + } + + @Override + public Path getPathForLocalArtifact(Artifact artifact) { + return null; + } + + @Override + public Path getPathForRemoteArtifact(RemoteRepository remote, Artifact artifact) { + return null; + } + + @Override + public Version parseVersion(String version) { + return null; + } + + @Override + public VersionRange parseVersionRange(String versionRange) { + return null; + } + + @Override + public VersionConstraint parseVersionConstraint(String s) { + return null; + } + + @Override + public Map> resolveDependencies( + DependencyCoordinate dependencyCoordinate, PathScope scope, Collection desiredTypes) { + return Map.of(); + } + + @Override + public Map> resolveDependencies( + Project project, PathScope scope, Collection desiredTypes) { + return Map.of(); + } + + @Override + public Type requireType(String id) { + return null; + } + + @Override + public Language requireLanguage(String id) { + return null; + } + + @Override + public Packaging requirePackaging(String id) { + return null; + } + + @Override + public ProjectScope requireProjectScope(String id) { + return null; + } + + @Override + public DependencyScope requireDependencyScope(String id) { + return null; + } + + @Override + public PathScope requirePathScope(String id) { + return null; } } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/AbstractMojoTestCase.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/AbstractMojoTestCase.java deleted file mode 100644 index c2b2309..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/AbstractMojoTestCase.java +++ /dev/null @@ -1,723 +0,0 @@ -/* - * 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.plugin.testing; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Field; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import com.google.inject.Module; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; -import org.apache.maven.artifact.handler.DefaultArtifactHandler; -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.apache.maven.execution.DefaultMavenExecutionRequest; -import org.apache.maven.execution.DefaultMavenExecutionResult; -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionResult; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.lifecycle.internal.MojoDescriptorCreator; -import org.apache.maven.model.Plugin; -import org.apache.maven.plugin.Mojo; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.plugin.PluginParameterExpressionEvaluator; -import org.apache.maven.plugin.descriptor.MojoDescriptor; -import org.apache.maven.plugin.descriptor.Parameter; -import org.apache.maven.plugin.descriptor.PluginDescriptor; -import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; -import org.apache.maven.project.MavenProject; -import org.apache.maven.repository.internal.MavenRepositorySystemUtils; -import org.codehaus.plexus.ContainerConfiguration; -import org.codehaus.plexus.DefaultContainerConfiguration; -import org.codehaus.plexus.DefaultPlexusContainer; -import org.codehaus.plexus.PlexusConstants; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.PlexusContainerException; -import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.classworlds.ClassWorld; -import org.codehaus.plexus.component.configurator.ComponentConfigurationException; -import org.codehaus.plexus.component.configurator.ComponentConfigurator; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.configuration.PlexusConfiguration; -import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; -import org.codehaus.plexus.context.Context; -import org.codehaus.plexus.util.InterpolationFilterReader; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.ReflectionUtils; -import org.codehaus.plexus.util.StringUtils; -import org.codehaus.plexus.util.xml.XmlStreamReader; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; - -/** - * TODO: add a way to use the plugin POM for the lookup so that the user doesn't have to provide the a:g:v:goal - * as the role hint for the mojo lookup. - * TODO: standardize the execution of the mojo and looking at the results, but could simply have a template method - * for verifying the state of the mojo post execution - * TODO: need a way to look at the state of the mojo without adding getters, this could be where we finally specify - * the expressions which extract values from the mojo. - * TODO: create a standard directory structure for picking up POMs to make this even easier, we really just need a testing - * descriptor and make this entirely declarative! - * - * @author jesse - */ -public abstract class AbstractMojoTestCase extends PlexusTestCase { - private static final DefaultArtifactVersion MAVEN_VERSION; - - static { - DefaultArtifactVersion version = null; - String path = "/META-INF/maven/org.apache.maven/maven-core/pom.properties"; - - try (InputStream is = AbstractMojoTestCase.class.getResourceAsStream(path)) { - Properties properties = new Properties(); - if (is != null) { - properties.load(is); - } - String property = properties.getProperty("version"); - if (property != null) { - version = new DefaultArtifactVersion(property); - } - } catch (IOException e) { - // odd, where did this come from - } - MAVEN_VERSION = version; - } - - private ComponentConfigurator configurator; - - private PlexusContainer container; - - private Map mojoDescriptors; - - /* - * for the harness I think we have decided against going the route of using the maven project builder. - * instead I think we are going to try and make an instance of the localrespository and assign that - * to either the project stub or into the mojo directly with injection...not sure yet though. - */ - // private MavenProjectBuilder projectBuilder; - @Override - protected void setUp() throws Exception { - assertTrue( - "Maven 3.2.4 or better is required", - MAVEN_VERSION == null || new DefaultArtifactVersion("3.2.3").compareTo(MAVEN_VERSION) < 0); - - configurator = getContainer().lookup(ComponentConfigurator.class, "basic"); - Context context = container.getContext(); - Map map = context.getContextData(); - - try (InputStream is = getClass().getResourceAsStream("/" + getPluginDescriptorLocation()); - Reader reader = new BufferedReader(new XmlStreamReader(is)); - InterpolationFilterReader interpolationReader = new InterpolationFilterReader(reader, map, "${", "}")) { - - PluginDescriptor pluginDescriptor = new PluginDescriptorBuilder().build(interpolationReader); - - Artifact artifact = new DefaultArtifact( - pluginDescriptor.getGroupId(), - pluginDescriptor.getArtifactId(), - pluginDescriptor.getVersion(), - null, - "jar", - null, - new DefaultArtifactHandler("jar")); - - artifact.setFile(getPluginArtifactFile()); - pluginDescriptor.setPluginArtifact(artifact); - pluginDescriptor.setArtifacts(Arrays.asList(artifact)); - - for (ComponentDescriptor desc : pluginDescriptor.getComponents()) { - getContainer().addComponentDescriptor(desc); - } - - mojoDescriptors = new HashMap<>(); - for (MojoDescriptor mojoDescriptor : pluginDescriptor.getMojos()) { - mojoDescriptors.put(mojoDescriptor.getGoal(), mojoDescriptor); - } - } - } - - /** - * Returns best-effort plugin artifact file. - *

- * First, attempts to determine parent directory of META-INF directory holding the plugin descriptor. If META-INF - * parent directory cannot be determined, falls back to test basedir. - */ - private File getPluginArtifactFile() throws IOException { - final String pluginDescriptorLocation = getPluginDescriptorLocation(); - final URL resource = getClass().getResource("/" + pluginDescriptorLocation); - - File file = null; - - // attempt to resolve relative to META-INF/maven/plugin.xml first - if (resource != null) { - if ("file".equalsIgnoreCase(resource.getProtocol())) { - String path = resource.getPath(); - if (path.endsWith(pluginDescriptorLocation)) { - file = new File(path.substring(0, path.length() - pluginDescriptorLocation.length())); - } - } else if ("jar".equalsIgnoreCase(resource.getProtocol())) { - // TODO is there a helper for this somewhere? - try { - URL jarfile = new URL(resource.getPath()); - if ("file".equalsIgnoreCase(jarfile.getProtocol())) { - String path = jarfile.getPath(); - if (path.endsWith(pluginDescriptorLocation)) { - file = new File(path.substring(0, path.length() - pluginDescriptorLocation.length() - 2)); - } - } - } catch (MalformedURLException e) { - // not jar:file:/ URL, too bad - } - } - } - - // fallback to test project basedir if couldn't resolve relative to META-INF/maven/plugin.xml - if (file == null || !file.exists()) { - file = new File(getBasedir()); - } - - return file.getCanonicalFile(); - } - - protected InputStream getPublicDescriptorStream() throws Exception { - return new FileInputStream(new File(getPluginDescriptorPath())); - } - - protected String getPluginDescriptorPath() { - return getBasedir() + "/target/classes/META-INF/maven/plugin.xml"; - } - - protected String getPluginDescriptorLocation() { - return "META-INF/maven/plugin.xml"; - } - - @Override - protected void setupContainer() { - ContainerConfiguration cc = setupContainerConfiguration(); - try { - List modules = new ArrayList<>(); - addGuiceModules(modules); - container = new DefaultPlexusContainer(cc, modules.toArray(new Module[0])); - } catch (PlexusContainerException e) { - e.printStackTrace(); - fail("Failed to create plexus container."); - } - } - - /** - * @since 3.0.0 - */ - protected void addGuiceModules(List modules) { - // no custom guice modules by default - } - - protected ContainerConfiguration setupContainerConfiguration() { - ClassWorld classWorld = - new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader()); - - ContainerConfiguration cc = new DefaultContainerConfiguration() - .setClassWorld(classWorld) - .setClassPathScanning(PlexusConstants.SCANNING_INDEX) - .setAutoWiring(true) - .setName("maven"); - - return cc; - } - - @Override - protected PlexusContainer getContainer() { - if (container == null) { - setupContainer(); - } - - return container; - } - - /** - * Lookup the mojo leveraging the subproject pom - * - * @param goal - * @param pluginPom - * @return a Mojo instance - * @throws Exception - */ - protected T lookupMojo(String goal, String pluginPom) throws Exception { - return lookupMojo(goal, new File(pluginPom)); - } - - /** - * Lookup an empty mojo - * - * @param goal - * @param pluginPom - * @return a Mojo instance - * @throws Exception - */ - protected T lookupEmptyMojo(String goal, String pluginPom) throws Exception { - return lookupEmptyMojo(goal, new File(pluginPom)); - } - - /** - * Lookup the mojo leveraging the actual subprojects pom - * - * @param goal - * @param pom - * @return a Mojo instance - * @throws Exception - */ - protected T lookupMojo(String goal, File pom) throws Exception { - File pluginPom = new File(getBasedir(), "pom.xml"); - - Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(pluginPom)); - - String artifactId = pluginPomDom.getChild("artifactId").getValue(); - - String groupId = resolveFromRootThenParent(pluginPomDom, "groupId"); - - String version = resolveFromRootThenParent(pluginPomDom, "version"); - - PlexusConfiguration pluginConfiguration = extractPluginConfiguration(artifactId, pom); - - return lookupMojo(groupId, artifactId, version, goal, pluginConfiguration); - } - - /** - * Lookup the mojo leveraging the actual subprojects pom - * - * @param goal - * @param pom - * @return a Mojo instance - * @throws Exception - */ - protected T lookupEmptyMojo(String goal, File pom) throws Exception { - File pluginPom = new File(getBasedir(), "pom.xml"); - - Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(pluginPom)); - - String artifactId = pluginPomDom.getChild("artifactId").getValue(); - - String groupId = resolveFromRootThenParent(pluginPomDom, "groupId"); - - String version = resolveFromRootThenParent(pluginPomDom, "version"); - - return lookupMojo(groupId, artifactId, version, goal, null); - } - - /* - protected Mojo lookupMojo( String groupId, String artifactId, String version, String goal, File pom ) - throws Exception - { - PlexusConfiguration pluginConfiguration = extractPluginConfiguration( artifactId, pom ); - - return lookupMojo( groupId, artifactId, version, goal, pluginConfiguration ); - } - */ - /** - * lookup the mojo while we have all of the relavent information - * - * @param groupId - * @param artifactId - * @param version - * @param goal - * @param pluginConfiguration - * @return a Mojo instance - * @throws Exception - */ - protected T lookupMojo( - String groupId, String artifactId, String version, String goal, PlexusConfiguration pluginConfiguration) - throws Exception { - validateContainerStatus(); - - // pluginkey = groupId : artifactId : version : goal - - T mojo = (T) lookup(Mojo.class, groupId + ":" + artifactId + ":" + version + ":" + goal); - - if (pluginConfiguration != null) { - /* requires v10 of plexus container for lookup on expression evaluator - ExpressionEvaluator evaluator = (ExpressionEvaluator) getContainer().lookup( ExpressionEvaluator.ROLE, - "stub-evaluator" ); - */ - ExpressionEvaluator evaluator = new ResolverExpressionEvaluatorStub(); - - configurator.configureComponent( - mojo, pluginConfiguration, evaluator, getContainer().getContainerRealm()); - } - - return mojo; - } - - /** - * - * @param project - * @param goal - * @return - * @throws Exception - * @since 2.0 - */ - protected T lookupConfiguredMojo(MavenProject project, String goal) throws Exception { - return lookupConfiguredMojo(newMavenSession(project), newMojoExecution(goal)); - } - - /** - * - * @param session - * @param execution - * @return - * @throws Exception - * @throws ComponentConfigurationException - * @since 2.0 - */ - protected T lookupConfiguredMojo(MavenSession session, MojoExecution execution) - throws Exception, ComponentConfigurationException { - MavenProject project = session.getCurrentProject(); - MojoDescriptor mojoDescriptor = execution.getMojoDescriptor(); - - T mojo = (T) lookup(mojoDescriptor.getRole(), mojoDescriptor.getRoleHint()); - - ExpressionEvaluator evaluator = new PluginParameterExpressionEvaluator(session, execution); - - Xpp3Dom configuration = null; - Plugin plugin = project.getPlugin(mojoDescriptor.getPluginDescriptor().getPluginLookupKey()); - if (plugin != null) { - configuration = (Xpp3Dom) plugin.getConfiguration(); - } - if (configuration == null) { - configuration = new Xpp3Dom("configuration"); - } - configuration = Xpp3Dom.mergeXpp3Dom(configuration, execution.getConfiguration()); - - PlexusConfiguration pluginConfiguration = new XmlPlexusConfiguration(configuration); - - if (mojoDescriptor.getComponentConfigurator() != null) { - configurator = - getContainer().lookup(ComponentConfigurator.class, mojoDescriptor.getComponentConfigurator()); - } - - configurator.configureComponent( - mojo, pluginConfiguration, evaluator, getContainer().getContainerRealm()); - - return mojo; - } - - /** - * - * @param project - * @return - * @since 2.0 - */ - protected MavenSession newMavenSession(MavenProject project) { - MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - MavenExecutionResult result = new DefaultMavenExecutionResult(); - - MavenSession session = new MavenSession(container, MavenRepositorySystemUtils.newSession(), request, result); - session.setCurrentProject(project); - session.setProjects(Arrays.asList(project)); - return session; - } - - /** - * - * @param goal - * @return - * @since 2.0 - */ - protected MojoExecution newMojoExecution(String goal) { - MojoDescriptor mojoDescriptor = mojoDescriptors.get(goal); - assertNotNull(String.format("The MojoDescriptor for the goal %s cannot be null.", goal), mojoDescriptor); - MojoExecution execution = new MojoExecution(mojoDescriptor); - finalizeMojoConfiguration(execution); - return execution; - } - - // copy&paste from o.a.m.l.i.DefaultLifecycleExecutionPlanCalculator.finalizeMojoConfiguration(MojoExecution) - private void finalizeMojoConfiguration(MojoExecution mojoExecution) { - MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); - - Xpp3Dom executionConfiguration = mojoExecution.getConfiguration(); - if (executionConfiguration == null) { - executionConfiguration = new Xpp3Dom("configuration"); - } - - Xpp3Dom defaultConfiguration = new Xpp3Dom(MojoDescriptorCreator.convert(mojoDescriptor)); - - Xpp3Dom finalConfiguration = new Xpp3Dom("configuration"); - - if (mojoDescriptor.getParameters() != null) { - for (Parameter parameter : mojoDescriptor.getParameters()) { - Xpp3Dom parameterConfiguration = executionConfiguration.getChild(parameter.getName()); - - if (parameterConfiguration == null) { - parameterConfiguration = executionConfiguration.getChild(parameter.getAlias()); - } - - Xpp3Dom parameterDefaults = defaultConfiguration.getChild(parameter.getName()); - - parameterConfiguration = Xpp3Dom.mergeXpp3Dom(parameterConfiguration, parameterDefaults, Boolean.TRUE); - - if (parameterConfiguration != null) { - parameterConfiguration = new Xpp3Dom(parameterConfiguration, parameter.getName()); - - if (StringUtils.isEmpty(parameterConfiguration.getAttribute("implementation")) - && StringUtils.isNotEmpty(parameter.getImplementation())) { - parameterConfiguration.setAttribute("implementation", parameter.getImplementation()); - } - - finalConfiguration.addChild(parameterConfiguration); - } - } - } - - mojoExecution.setConfiguration(finalConfiguration); - } - - /** - * @param artifactId - * @param pom - * @return the plexus configuration - * @throws Exception - */ - protected PlexusConfiguration extractPluginConfiguration(String artifactId, File pom) throws Exception { - - try (Reader reader = ReaderFactory.newXmlReader(pom)) { - Xpp3Dom pomDom = Xpp3DomBuilder.build(reader); - return extractPluginConfiguration(artifactId, pomDom); - } - } - - /** - * @param artifactId - * @param pomDom - * @return the plexus configuration - * @throws Exception - */ - protected PlexusConfiguration extractPluginConfiguration(String artifactId, Xpp3Dom pomDom) throws Exception { - Xpp3Dom pluginConfigurationElement = null; - - Xpp3Dom buildElement = pomDom.getChild("build"); - if (buildElement != null) { - Xpp3Dom pluginsRootElement = buildElement.getChild("plugins"); - - if (pluginsRootElement != null) { - Xpp3Dom[] pluginElements = pluginsRootElement.getChildren(); - - for (Xpp3Dom pluginElement : pluginElements) { - String pluginElementArtifactId = - pluginElement.getChild("artifactId").getValue(); - - if (pluginElementArtifactId.equals(artifactId)) { - pluginConfigurationElement = pluginElement.getChild("configuration"); - - break; - } - } - - if (pluginConfigurationElement == null) { - throw new ConfigurationException("Cannot find a configuration element for a plugin with an " - + "artifactId of " + artifactId + "."); - } - } - } - - if (pluginConfigurationElement == null) { - throw new ConfigurationException( - "Cannot find a configuration element for a plugin with an artifactId of " + artifactId + "."); - } - - return new XmlPlexusConfiguration(pluginConfigurationElement); - } - - /** - * Configure the mojo - * - * @param mojo - * @param artifactId - * @param pom - * @return a Mojo instance - * @throws Exception - */ - protected T configureMojo(T mojo, String artifactId, File pom) throws Exception { - validateContainerStatus(); - - PlexusConfiguration pluginConfiguration = extractPluginConfiguration(artifactId, pom); - - ExpressionEvaluator evaluator = new ResolverExpressionEvaluatorStub(); - - configurator.configureComponent( - mojo, pluginConfiguration, evaluator, getContainer().getContainerRealm()); - - return mojo; - } - - /** - * Configure the mojo with the given plexus configuration - * - * @param mojo - * @param pluginConfiguration - * @return a Mojo instance - * @throws Exception - */ - protected T configureMojo(T mojo, PlexusConfiguration pluginConfiguration) throws Exception { - validateContainerStatus(); - - ExpressionEvaluator evaluator = new ResolverExpressionEvaluatorStub(); - - configurator.configureComponent( - mojo, pluginConfiguration, evaluator, getContainer().getContainerRealm()); - - return mojo; - } - - /** - * Convenience method to obtain the value of a variable on a mojo that might not have a getter. - * - * NOTE: the caller is responsible for casting to to what the desired type is. - * - * @param object - * @param variable - * @return object value of variable - * @throws IllegalArgumentException - */ - protected T getVariableValueFromObject(Object object, String variable) throws IllegalAccessException { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); - - field.setAccessible(true); - - return (T) field.get(object); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - * - * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - * - * @param object - * @return map of variable names and values - */ - protected Map getVariablesAndValuesFromObject(Object object) throws IllegalAccessException { - return getVariablesAndValuesFromObject(object.getClass(), object); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - * - * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - * - * @param clazz - * @param object - * @return map of variable names and values - */ - protected Map getVariablesAndValuesFromObject(Class clazz, Object object) - throws IllegalAccessException { - Map map = new HashMap<>(); - - Field[] fields = clazz.getDeclaredFields(); - - AccessibleObject.setAccessible(fields, true); - - for (Field field : fields) { - map.put(field.getName(), field.get(object)); - } - - Class superclass = clazz.getSuperclass(); - - if (!Object.class.equals(superclass)) { - map.putAll(getVariablesAndValuesFromObject(superclass, object)); - } - - return map; - } - - /** - * Convenience method to set values to variables in objects that don't have setters - * - * @param object - * @param variable - * @param value - * @throws IllegalAccessException - */ - protected void setVariableValueToObject(Object object, String variable, T value) throws IllegalAccessException { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); - - field.setAccessible(true); - - field.set(object, value); - } - - /** - * sometimes the parent element might contain the correct value so generalize that access - * - * TODO find out where this is probably done elsewhere - * - * @param pluginPomDom - * @param element - * @return - * @throws Exception - */ - private String resolveFromRootThenParent(Xpp3Dom pluginPomDom, String element) throws Exception { - Xpp3Dom elementDom = pluginPomDom.getChild(element); - - // parent might have the group Id so resolve it - if (elementDom == null) { - Xpp3Dom pluginParentDom = pluginPomDom.getChild("parent"); - - if (pluginParentDom != null) { - elementDom = pluginParentDom.getChild(element); - - if (elementDom == null) { - throw new Exception("unable to determine " + element); - } - - return elementDom.getValue(); - } - - throw new Exception("unable to determine " + element); - } - - return elementDom.getValue(); - } - - /** - * We should make sure this is called in each method that makes use of the container, - * otherwise we throw ugly NPE's - * - * crops up when the subclassing code defines the setUp method but doesn't call super.setUp() - * - * @throws Exception - */ - private void validateContainerStatus() throws Exception { - if (getContainer() != null) { - return; - } - - throw new Exception("container is null, make sure super.setUp() is called"); - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ArtifactStubFactory.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ArtifactStubFactory.java deleted file mode 100644 index d510314..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ArtifactStubFactory.java +++ /dev/null @@ -1,510 +0,0 @@ -/* - * 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.plugin.testing; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.HashSet; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; -import org.apache.maven.artifact.handler.ArtifactHandler; -import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.plugin.testing.stubs.DefaultArtifactHandlerStub; -import org.codehaus.plexus.archiver.Archiver; -import org.codehaus.plexus.archiver.ArchiverException; -import org.codehaus.plexus.archiver.manager.ArchiverManager; -import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; -import org.codehaus.plexus.archiver.war.WarArchiver; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.ReflectionUtils; -import org.codehaus.plexus.util.StringUtils; - -/** - * This class creates artifacts to be used for testing purposes. It can optionally create actual files on the local disk - * for things like copying. It can create these files as archives with named files inside to be used for testing things - * like unpack. Also provided are some utility methods to quickly get a set of artifacts distinguished by various things - * like group,artifact,type,scope, etc It was originally developed for the dependency plugin, but can be useful in other - * plugins that need to simulate artifacts for unit tests. - * - * @author Brian Fox - */ -public class ArtifactStubFactory { - private File workingDir; - - private boolean createFiles; - - private File srcFile; - - private boolean createUnpackableFile; - - private ArchiverManager archiverManager; - - /** - * Default constructor. This should be used only if real files aren't needed...just the artifact objects - */ - public ArtifactStubFactory() { - this.workingDir = null; - this.createFiles = false; - } - - /** - * This constructor is to be used if files are needed and to set a working dir - * - * @param workingDir - * @param createFiles - */ - public ArtifactStubFactory(File workingDir, boolean createFiles) { - this.workingDir = new File(workingDir, "localTestRepo"); - this.createFiles = createFiles; - } - - /** - * If set, the file will be created as a zip/jar/war with a file inside that can be checked to exist after - * unpacking. - * - * @param archiverManager - */ - public void setUnpackableFile(ArchiverManager archiverManager) { - this.createUnpackableFile = true; - this.archiverManager = archiverManager; - } - - /** - * @param groupId - * @param artifactId - * @param version - * @return a DefaultArtifact instance for the given parameters - * @throws IOException if any - * @see #createArtifact(String, String, String, String, String, String) - */ - public Artifact createArtifact(String groupId, String artifactId, String version) throws IOException { - return createArtifact(groupId, artifactId, version, Artifact.SCOPE_COMPILE, "jar", ""); - } - - /** - * @param groupId - * @param artifactId - * @param version - * @param scope - * @return a DefaultArtifact instance for the given parameters - * @throws IOException if any - * @see #createArtifact(String, String, String, String, String, String) - */ - public Artifact createArtifact(String groupId, String artifactId, String version, String scope) throws IOException { - return createArtifact(groupId, artifactId, version, scope, "jar", ""); - } - - /** - * @param groupId - * @param artifactId - * @param version - * @param scope - * @param type - * @param classifier - * @return a DefaultArtifact instance for the given parameters - * @throws IOException if any - * @see #createArtifact(String, String, VersionRange, String, String, String, boolean) - */ - public Artifact createArtifact( - String groupId, String artifactId, String version, String scope, String type, String classifier) - throws IOException { - VersionRange vr = VersionRange.createFromVersion(version); - return createArtifact(groupId, artifactId, vr, scope, type, classifier, false); - } - - /** - * @param groupId not null - * @param artifactId not null - * @param versionRange not null - * @param scope not null - * @param type not null - * @param classifier - * @param optional not null - * @return a DefaultArtifact instance - * @throws IOException if any - */ - public Artifact createArtifact( - String groupId, - String artifactId, - VersionRange versionRange, - String scope, - String type, - String classifier, - boolean optional) - throws IOException { - ArtifactHandler ah = new DefaultArtifactHandlerStub(type, classifier); - - Artifact artifact = - new DefaultArtifact(groupId, artifactId, versionRange, scope, type, classifier, ah, optional); - - // i have no idea why this needs to be done manually when isSnapshot is able to figure it out. - artifact.setRelease(!artifact.isSnapshot()); - - if (createFiles) { - setArtifactFile(artifact, this.workingDir, this.srcFile, this.createUnpackableFile); - } - return artifact; - } - - /** - * Creates a new empty file and attaches it to the artifact. - * - * @param artifact to attach the file to. - * @param workingDir where to locate the new file - * @throws IOException - */ - public void setArtifactFile(Artifact artifact, File workingDir) throws IOException { - setArtifactFile(artifact, workingDir, null, false); - } - - /** - * Copyies the srcFile to the workingDir and then attaches it to the artifact. If srcFile is null, a new empty file - * will be created. - * - * @param artifact to attach - * @param workingDir where to copy the srcFile. - * @param srcFile file to be attached. - * @throws IOException - */ - public void setArtifactFile(Artifact artifact, File workingDir, File srcFile) throws IOException { - setArtifactFile(artifact, workingDir, srcFile, false); - } - - /** - * Creates an unpackable file (zip,jar etc) containing an empty file. - * - * @param artifact to attach - * @param workingDir where to create the file. - * @throws IOException - */ - public void setUnpackableArtifactFile(Artifact artifact, File workingDir) throws IOException { - setArtifactFile(artifact, workingDir, null, true); - } - - /** - * Creates an unpackable file (zip,jar etc) containing the srcFile. If srcFile is null, a new empty file will be - * created. - * - * @param artifact to attach - * @param workingDir where to create the file. - * @param srcFile - * @throws IOException if any - */ - public void setUnpackableArtifactFile(Artifact artifact, File workingDir, File srcFile) throws IOException { - setArtifactFile(artifact, workingDir, srcFile, true); - } - - /** - * Creates a file that can be copied or unpacked based on the passed in artifact - * - * @param artifact - * @param workingDir - * @param srcFile - * @param createUnpackableFile - * @throws IOException if any - */ - private void setArtifactFile(Artifact artifact, File workingDir, File srcFile, boolean createUnpackableFile) - throws IOException { - if (workingDir == null) { - throw new IllegalArgumentException("The workingDir must be set."); - } - - String fileName = getFormattedFileName(artifact, false); - - File theFile = new File(workingDir, fileName); - theFile.getParentFile().mkdirs(); - - if (srcFile == null) { - theFile.createNewFile(); - } else if (createUnpackableFile) { - try { - createUnpackableFile(artifact, theFile); - } catch (NoSuchArchiverException e) { - throw new IOException("NoSuchArchiverException: " + e.getMessage()); - } catch (ArchiverException e) { - throw new IOException("ArchiverException: " + e.getMessage()); - } - } else { - FileUtils.copyFile(srcFile, theFile); - } - - artifact.setFile(theFile); - } - - /** - * @param artifact - * @return - */ - public static String getUnpackableFileName(Artifact artifact) { - return "" + artifact.getGroupId() + "-" + artifact.getArtifactId() + "-" + artifact.getVersion() + "-" - + artifact.getClassifier() + "-" + artifact.getType() + ".txt"; - } - - /** - * @param artifact - * @param destFile - * @throws NoSuchArchiverException - * @throws ArchiverException if any - * @throws IOException if any - */ - public void createUnpackableFile(Artifact artifact, File destFile) - throws NoSuchArchiverException, ArchiverException, IOException { - Archiver archiver = archiverManager.getArchiver(destFile); - - archiver.setDestFile(destFile); - archiver.addFile(srcFile, getUnpackableFileName(artifact)); - - if (archiver instanceof WarArchiver) { - WarArchiver war = (WarArchiver) archiver; - war.setExpectWebXml(false); - } - archiver.createArchive(); - } - - /** - * @return a DefaultArtifact instance for testGroupId:release:jar:1.0 - * @throws IOException if any - */ - public Artifact getReleaseArtifact() throws IOException { - return createArtifact("testGroupId", "release", "1.0"); - } - - /** - * @return a default DefaultArtifact instance for testGroupId:snapshot:jar:2.0-SNAPSHOT - * @throws IOException if any - */ - public Artifact getSnapshotArtifact() throws IOException { - return createArtifact("testGroupId", "snapshot", "2.0-SNAPSHOT"); - } - - /** - * @return a default set of release and snapshot DefaultArtifact, i.e.: - * testGroupId:snapshot:jar:2.0-SNAPSHOT, testGroupId:release:jar:1.0 - * @throws IOException if any - * @see #getReleaseArtifact() - * @see #getSnapshotArtifact() - */ - public Set getReleaseAndSnapshotArtifacts() throws IOException { - Set set = new HashSet<>(); - set.add(getReleaseArtifact()); - set.add(getSnapshotArtifact()); - return set; - } - - /** - * @return a default set of DefaultArtifact, i.e.: - * g:provided:jar:1.0, g:compile:jar:1.0, g:system:jar:1.0, g:test:jar:1.0, g:runtime:jar:1.0 - * @throws IOException if any - */ - public Set getScopedArtifacts() throws IOException { - Set set = new HashSet<>(); - set.add(createArtifact("g", "compile", "1.0", Artifact.SCOPE_COMPILE)); - set.add(createArtifact("g", "provided", "1.0", Artifact.SCOPE_PROVIDED)); - set.add(createArtifact("g", "test", "1.0", Artifact.SCOPE_TEST)); - set.add(createArtifact("g", "runtime", "1.0", Artifact.SCOPE_RUNTIME)); - set.add(createArtifact("g", "system", "1.0", Artifact.SCOPE_SYSTEM)); - return set; - } - - /** - * @return a set of DefaultArtifact, i.e.: - * g:d:zip:1.0, g:a:war:1.0, g:b:jar:1.0, g:c:sources:1.0, g:e:rar:1.0 - * @throws IOException if any - */ - public Set getTypedArtifacts() throws IOException { - Set set = new HashSet<>(); - set.add(createArtifact("g", "a", "1.0", Artifact.SCOPE_COMPILE, "war", null)); - set.add(createArtifact("g", "b", "1.0", Artifact.SCOPE_COMPILE, "jar", null)); - set.add(createArtifact("g", "c", "1.0", Artifact.SCOPE_COMPILE, "sources", null)); - set.add(createArtifact("g", "d", "1.0", Artifact.SCOPE_COMPILE, "zip", null)); - set.add(createArtifact("g", "e", "1.0", Artifact.SCOPE_COMPILE, "rar", null)); - return set; - } - - /** - * @return a set of DefaultArtifact, i.e.: - * g:c:jar:three:1.0, g:b:jar:two:1.0, g:d:jar:four:1.0, g:a:jar:one:1.0 - * @throws IOException if any - */ - public Set getClassifiedArtifacts() throws IOException { - Set set = new HashSet<>(); - set.add(createArtifact("g", "a", "1.0", Artifact.SCOPE_COMPILE, "jar", "one")); - set.add(createArtifact("g", "b", "1.0", Artifact.SCOPE_COMPILE, "jar", "two")); - set.add(createArtifact("g", "c", "1.0", Artifact.SCOPE_COMPILE, "jar", "three")); - set.add(createArtifact("g", "d", "1.0", Artifact.SCOPE_COMPILE, "jar", "four")); - return set; - } - - /** - * @return a set of DefaultArtifact, i.e.: - * g:d:zip:1.0, g:a:war:1.0, g:b:jar:1.0, g:e:rar:1.0 - * @throws IOException if any - */ - public Set getTypedArchiveArtifacts() throws IOException { - Set set = new HashSet<>(); - set.add(createArtifact("g", "a", "1.0", Artifact.SCOPE_COMPILE, "war", null)); - set.add(createArtifact("g", "b", "1.0", Artifact.SCOPE_COMPILE, "jar", null)); - set.add(createArtifact("g", "d", "1.0", Artifact.SCOPE_COMPILE, "zip", null)); - set.add(createArtifact("g", "e", "1.0", Artifact.SCOPE_COMPILE, "rar", null)); - return set; - } - - /** - * @return a set of DefaultArtifact, i.e.: - * g:one:jar:a:1.0, g:two:jar:a:1.0, g:four:jar:a:1.0, g:three:jar:a:1.0 - * @throws IOException if any - */ - public Set getArtifactArtifacts() throws IOException { - Set set = new HashSet<>(); - set.add(createArtifact("g", "one", "1.0", Artifact.SCOPE_COMPILE, "jar", "a")); - set.add(createArtifact("g", "two", "1.0", Artifact.SCOPE_COMPILE, "jar", "a")); - set.add(createArtifact("g", "three", "1.0", Artifact.SCOPE_COMPILE, "jar", "a")); - set.add(createArtifact("g", "four", "1.0", Artifact.SCOPE_COMPILE, "jar", "a")); - return set; - } - - /** - * @return a set of DefaultArtifact, i.e.: - * one:group-one:jar:a:1.0, three:group-three:jar:a:1.0, four:group-four:jar:a:1.0, - * two:group-two:jar:a:1.0 - * @throws IOException if any - */ - public Set getGroupIdArtifacts() throws IOException { - Set set = new HashSet<>(); - set.add(createArtifact("one", "group-one", "1.0", Artifact.SCOPE_COMPILE, "jar", "a")); - set.add(createArtifact("two", "group-two", "1.0", Artifact.SCOPE_COMPILE, "jar", "a")); - set.add(createArtifact("three", "group-three", "1.0", Artifact.SCOPE_COMPILE, "jar", "a")); - set.add(createArtifact("four", "group-four", "1.0", Artifact.SCOPE_COMPILE, "jar", "a")); - return set; - } - - /** - * @return a set of DefaultArtifact - * @throws IOException if any - * @see #getTypedArtifacts() - * @see #getScopedArtifacts() - * @see #getReleaseAndSnapshotArtifacts() - */ - public Set getMixedArtifacts() throws IOException { - Set set = new HashSet<>(); - set.addAll(getTypedArtifacts()); - set.addAll(getScopedArtifacts()); - set.addAll(getReleaseAndSnapshotArtifacts()); - return set; - } - - /** - * @return Returns the createFiles. - */ - public boolean isCreateFiles() { - return this.createFiles; - } - - /** - * @param createFiles The createFiles to set. - */ - public void setCreateFiles(boolean createFiles) { - this.createFiles = createFiles; - } - - /** - * @return Returns the workingDir. - */ - public File getWorkingDir() { - return this.workingDir; - } - - /** - * @param workingDir The workingDir to set. - */ - public void setWorkingDir(File workingDir) { - this.workingDir = workingDir; - } - - /** - * @return Returns the srcFile. - */ - public File getSrcFile() { - return this.srcFile; - } - - /** - * @param srcFile The srcFile to set. - */ - public void setSrcFile(File srcFile) { - this.srcFile = srcFile; - } - - /** - * Convenience method to set values to variables in objects that don't have setters - * - * @param object - * @param variable - * @param value - * @throws IllegalAccessException - */ - public static void setVariableValueToObject(Object object, String variable, Object value) - throws IllegalAccessException { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); - - field.setAccessible(true); - - field.set(object, value); - } - - /** - * Builds the file name. If removeVersion is set, then the file name must be reconstructed from the artifactId, - * Classifier (if used) and Type. Otherwise, this method returns the artifact file name. - * - * @param artifact File to be formatted. - * @param removeVersion Specifies if the version should be removed from the file name. - * @return Formatted file name in the format artifactId-[version]-[classifier].[type] - */ - public static String getFormattedFileName(Artifact artifact, boolean removeVersion) { - String destFileName = null; - - // if there is a file and we aren't stripping the version, just get the - // name directly - if (artifact.getFile() != null && !removeVersion) { - destFileName = artifact.getFile().getName(); - } else - // if offline - { - String versionString = null; - if (!removeVersion) { - versionString = "-" + artifact.getVersion(); - } else { - versionString = ""; - } - - String classifierString = ""; - - if (StringUtils.isNotEmpty(artifact.getClassifier())) { - classifierString = "-" + artifact.getClassifier(); - } - - destFileName = artifact.getArtifactId() + versionString + classifierString + "." - + artifact.getArtifactHandler().getExtension(); - } - return destFileName; - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ConfigurationException.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ConfigurationException.java deleted file mode 100644 index 9b8150c..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ConfigurationException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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.plugin.testing; - -/** - * ConfigurationException - * - * @author jesse - */ -public class ConfigurationException extends Exception { - /** serialVersionUID */ - static final long serialVersionUID = -6180939638742159065L; - - /** - * @param message The detailed message. - */ - public ConfigurationException(String message) { - super(message); - } - - /** - * @param cause The detailed cause. - */ - public ConfigurationException(Throwable cause) { - super(cause); - } - - /** - * @param message The detailed message. - * @param cause The detailed cause. - */ - public ConfigurationException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoLogWrapper.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoLogWrapper.java deleted file mode 100644 index 869525c..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoLogWrapper.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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.plugin.testing; - -import org.apache.maven.plugin.logging.Log; -import org.slf4j.Logger; - -import static java.util.Objects.requireNonNull; - -/** - * @author jdcasey - */ -public class MojoLogWrapper implements Log { - private final Logger logger; - - public MojoLogWrapper(Logger logger) { - this.logger = requireNonNull(logger); - } - - public void debug(CharSequence content) { - logger.debug(toString(content)); - } - - private String toString(CharSequence content) { - if (content == null) { - return ""; - } else { - return content.toString(); - } - } - - @Override - public void debug(CharSequence content, Throwable error) { - logger.debug(toString(content), error); - } - - @Override - public void debug(Throwable error) { - logger.debug("", error); - } - - @Override - public void info(CharSequence content) { - logger.info(toString(content)); - } - - @Override - public void info(CharSequence content, Throwable error) { - logger.info(toString(content), error); - } - - @Override - public void info(Throwable error) { - logger.info("", error); - } - - @Override - public void warn(CharSequence content) { - logger.warn(toString(content)); - } - - @Override - public void warn(CharSequence content, Throwable error) { - logger.warn(toString(content), error); - } - - @Override - public void warn(Throwable error) { - logger.warn("", error); - } - - @Override - public void error(CharSequence content) { - logger.error(toString(content)); - } - - @Override - public void error(CharSequence content, Throwable error) { - logger.error(toString(content), error); - } - - @Override - public void error(Throwable error) { - logger.error("", error); - } - - @Override - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - @Override - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - @Override - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - @Override - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoParameters.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoParameters.java deleted file mode 100644 index 842fba6..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoParameters.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.plugin.testing; - -import org.codehaus.plexus.util.xml.Xpp3Dom; - -/** - * Static helpers to create and manipulate mojo execution configuration parameters - * - * @since 3.2.0 - */ -public class MojoParameters { - public static Xpp3Dom newParameter(String name, String value) { - Xpp3Dom child = new Xpp3Dom(name); - child.setValue(value); - return child; - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoRule.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoRule.java deleted file mode 100644 index 878d750..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoRule.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * 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.plugin.testing; - -import java.io.File; -import java.io.InputStream; -import java.util.Map; - -import org.apache.maven.api.Session; -import org.apache.maven.execution.DefaultMavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.execution.MojoExecutionEvent; -import org.apache.maven.execution.MojoExecutionListener; -import org.apache.maven.execution.scope.internal.MojoExecutionScope; -import org.apache.maven.plugin.Mojo; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuilder; -import org.apache.maven.project.ProjectBuildingRequest; -import org.apache.maven.session.scope.internal.SessionScope; -import org.codehaus.plexus.ContainerConfiguration; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.component.configurator.ComponentConfigurationException; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.configuration.PlexusConfiguration; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.eclipse.aether.DefaultRepositorySystemSession; -import org.junit.Assert; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -/** - * {@link TestRule} for usage with Junit-4.10ff. This is just a wrapper for an embedded - * {@link AbstractMojoTestCase}, so all {@code protected} methods of the TestCase are - * exhibited as {@code public} in the rule. You may annotate single tests methods with - * {@link WithoutMojo} to prevent the rule from firing. - * - * @author Mirko Friedenhagen - * @since 2.2 - */ -public class MojoRule implements TestRule { - private final AbstractMojoTestCase testCase; - - public MojoRule() { - this(new AbstractMojoTestCase() {}); - } - - public MojoRule(AbstractMojoTestCase testCase) { - this.testCase = testCase; - } - - /** - * May be overridden in the implementation to do stuff after the embedded test case - * is set up but before the current test is actually run. - * - * @throws Throwable - */ - protected void before() throws Throwable {} - - /** - * May be overridden in the implementation to do stuff after the current test was run. - */ - protected void after() {} - - public InputStream getPublicDescriptorStream() throws Exception { - return testCase.getPublicDescriptorStream(); - } - - public String getPluginDescriptorPath() { - return testCase.getPluginDescriptorPath(); - } - - public String getPluginDescriptorLocation() { - return testCase.getPluginDescriptorLocation(); - } - - public void setupContainer() { - testCase.setupContainer(); - } - - public ContainerConfiguration setupContainerConfiguration() { - return testCase.setupContainerConfiguration(); - } - - public PlexusContainer getContainer() { - return testCase.getContainer(); - } - - /** - * Lookup the mojo leveraging the subproject pom - * - * @param goal - * @param pluginPom - * @return a Mojo instance - * @throws Exception - */ - public T lookupMojo(String goal, String pluginPom) throws Exception { - return testCase.lookupMojo(goal, pluginPom); - } - - /** - * Lookup an empty mojo - * - * @param goal - * @param pluginPom - * @return a Mojo instance - * @throws Exception - */ - public T lookupEmptyMojo(String goal, String pluginPom) throws Exception { - return testCase.lookupEmptyMojo(goal, new File(pluginPom)); - } - - /** - * Lookup the mojo leveraging the actual subprojects pom - * - * @param goal - * @param pom - * @return a Mojo instance - * @throws Exception - */ - public T lookupMojo(String goal, File pom) throws Exception { - return testCase.lookupMojo(goal, pom); - } - - /** - * Lookup the mojo leveraging the actual subprojects pom - * - * @param goal - * @param pom - * @return a Mojo instance - * @throws Exception - */ - public T lookupEmptyMojo(String goal, File pom) throws Exception { - return testCase.lookupEmptyMojo(goal, pom); - } - - public T lookupMojo( - String groupId, String artifactId, String version, String goal, PlexusConfiguration pluginConfiguration) - throws Exception { - return testCase.lookupMojo(groupId, artifactId, version, goal, pluginConfiguration); - } - - public T lookupConfiguredMojo(MavenProject project, String goal) throws Exception { - return testCase.lookupConfiguredMojo(project, goal); - } - - public T lookupConfiguredMojo(MavenSession session, MojoExecution execution) - throws Exception, ComponentConfigurationException { - return testCase.lookupConfiguredMojo(session, execution); - } - - public MavenSession newMavenSession(MavenProject project) { - return testCase.newMavenSession(project); - } - - public MojoExecution newMojoExecution(String goal) { - return testCase.newMojoExecution(goal); - } - - public PlexusConfiguration extractPluginConfiguration(String artifactId, File pom) throws Exception { - return testCase.extractPluginConfiguration(artifactId, pom); - } - - public PlexusConfiguration extractPluginConfiguration(String artifactId, Xpp3Dom pomDom) throws Exception { - return testCase.extractPluginConfiguration(artifactId, pomDom); - } - - public T configureMojo(T mojo, String artifactId, File pom) throws Exception { - return testCase.configureMojo(mojo, artifactId, pom); - } - - public T configureMojo(T mojo, PlexusConfiguration pluginConfiguration) throws Exception { - return testCase.configureMojo(mojo, pluginConfiguration); - } - - /** - * Convenience method to obtain the value of a variable on a mojo that might not have a getter. - * - * NOTE: the caller is responsible for casting to to what the desired type is. - * - * @param object - * @param variable - * @return object value of variable - * @throws IllegalArgumentException - */ - public T getVariableValueFromObject(Object object, String variable) throws IllegalAccessException { - return testCase.getVariableValueFromObject(object, variable); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - * - * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - * - * @param object - * @return map of variable names and values - */ - public Map getVariablesAndValuesFromObject(Object object) throws IllegalAccessException { - return testCase.getVariablesAndValuesFromObject(object); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - * - * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - * - * @param clazz - * @param object - * @return map of variable names and values - */ - public Map getVariablesAndValuesFromObject(Class clazz, Object object) - throws IllegalAccessException { - return testCase.getVariablesAndValuesFromObject(clazz, object); - } - - /** - * Convenience method to set values to variables in objects that don't have setters - * - * @param object - * @param variable - * @param value - * @throws IllegalAccessException - */ - public void setVariableValueToObject(Object object, String variable, T value) throws IllegalAccessException { - testCase.setVariableValueToObject(object, variable, value); - } - - @Override - public Statement apply(final Statement base, Description description) { - if (description.getAnnotation(WithoutMojo.class) != null) // skip. - { - return base; - } - return new Statement() { - @Override - public void evaluate() throws Throwable { - testCase.setUp(); - before(); - try { - base.evaluate(); - } finally { - after(); - } - } - }; - } - - /** - * @since 3.1.0 - */ - public MavenProject readMavenProject(File basedir) throws Exception { - File pom = new File(basedir, "pom.xml"); - MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - request.setBaseDirectory(basedir); - ProjectBuildingRequest configuration = request.getProjectBuildingRequest(); - configuration.setRepositorySession(new DefaultRepositorySystemSession()); - MavenProject project = - lookup(ProjectBuilder.class).build(pom, configuration).getProject(); - Assert.assertNotNull(project); - return project; - } - - /** - * @since 3.1.0 - */ - public void executeMojo(File basedir, String goal) throws Exception { - MavenProject project = readMavenProject(basedir); - MavenSession session = newMavenSession(project); - MojoExecution execution = newMojoExecution(goal); - executeMojo(session, project, execution); - } - - /** - * @since 3.1.0 - */ - public T lookupConfiguredMojo(File basedir, String goal) - throws Exception, ComponentConfigurationException { - MavenProject project = readMavenProject(basedir); - MavenSession session = newMavenSession(project); - MojoExecution execution = newMojoExecution(goal); - return lookupConfiguredMojo(session, execution); - } - - /** - * @since 3.1.0 - */ - public final T lookup(final Class role) throws ComponentLookupException { - return getContainer().lookup(role); - } - - /** - * @since 3.2.0 - */ - public void executeMojo(MavenProject project, String goal, Xpp3Dom... parameters) throws Exception { - MavenSession session = newMavenSession(project); - executeMojo(session, project, goal, parameters); - } - - /** - * @since 3.2.0 - */ - public void executeMojo(MavenSession session, MavenProject project, String goal, Xpp3Dom... parameters) - throws Exception { - MojoExecution execution = newMojoExecution(goal); - if (parameters != null) { - Xpp3Dom configuration = execution.getConfiguration(); - for (Xpp3Dom parameter : parameters) { - configuration.addChild(parameter); - } - } - executeMojo(session, project, execution); - } - - /** - * @since 3.2.0 - */ - public void executeMojo(MavenSession session, MavenProject project, MojoExecution execution) throws Exception { - SessionScope sessionScope = lookup(SessionScope.class); - try { - sessionScope.enter(); - sessionScope.seed(MavenSession.class, session); - sessionScope.seed(Session.class, session.getSession()); - - MojoExecutionScope executionScope = lookup(MojoExecutionScope.class); - try { - executionScope.enter(); - - executionScope.seed(MavenProject.class, project); - executionScope.seed(MojoExecution.class, execution); - - Mojo mojo = lookupConfiguredMojo(session, execution); - mojo.execute(); - - MojoExecutionEvent event = new MojoExecutionEvent(session, project, execution, mojo); - for (MojoExecutionListener listener : getContainer().lookupList(MojoExecutionListener.class)) { - listener.afterMojoExecutionSuccess(event); - } - } finally { - executionScope.exit(); - } - } finally { - sessionScope.exit(); - } - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ResolverExpressionEvaluatorStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ResolverExpressionEvaluatorStub.java deleted file mode 100644 index f4af2e7..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/ResolverExpressionEvaluatorStub.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * 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.plugin.testing; - -import java.io.File; - -import org.apache.maven.artifact.repository.MavenArtifactRepository; -import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; -import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; - -/** - * Stub for {@link ExpressionEvaluator} - * - * @author jesse - */ -public class ResolverExpressionEvaluatorStub implements ExpressionEvaluator { - /** {@inheritDoc} */ - @Override - public Object evaluate(String expr) throws ExpressionEvaluationException { - - Object value = null; - - if (expr == null) { - return null; - } - - String expression = stripTokens(expr); - - if (expression.equals(expr)) { - int index = expr.indexOf("${"); - if (index >= 0) { - int lastIndex = expr.indexOf("}", index); - if (lastIndex >= 0) { - String retVal = expr.substring(0, index); - - if (index > 0 && expr.charAt(index - 1) == '$') { - retVal += expr.substring(index + 1, lastIndex + 1); - } else { - retVal += evaluate(expr.substring(index, lastIndex + 1)); - } - - retVal += evaluate(expr.substring(lastIndex + 1)); - return retVal; - } - } - - // Was not an expression - if (expression.indexOf("$$") > -1) { - return expression.replaceAll("\\$\\$", "\\$"); - } - } - - if ("basedir".equals(expression) || "project.basedir".equals(expression)) { - return PlexusTestCase.getBasedir(); - } else if (expression.startsWith("basedir") || expression.startsWith("project.basedir")) { - int pathSeparator = expression.indexOf("/"); - - if (pathSeparator > 0) { - value = PlexusTestCase.getBasedir() + expression.substring(pathSeparator); - } else { - System.out.println("Got expression '" + expression + "' that was not recognised"); - } - return value; - } else if ("localRepository".equals(expression)) { - File localRepo = new File(PlexusTestCase.getBasedir(), "target/local-repo"); - return new MavenArtifactRepository( - "localRepository", - "file://" + localRepo.getAbsolutePath(), - new DefaultRepositoryLayout(), - null, - null); - } else { - return expr; - } - } - - private String stripTokens(String expr) { - if (expr.startsWith("${") && expr.indexOf("}") == expr.length() - 1) { - expr = expr.substring(2, expr.length() - 1); - } - - return expr; - } - - /** {@inheritDoc} */ - @Override - public File alignToBaseDirectory(File file) { - if (file.getAbsolutePath().startsWith(PlexusTestCase.getBasedir())) { - return file; - } else if (file.isAbsolute()) { - return file; - } else { - return new File(PlexusTestCase.getBasedir(), file.getPath()); - } - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/SilentLog.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/SilentLog.java deleted file mode 100644 index e94d81b..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/SilentLog.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * 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.plugin.testing; - -import org.apache.maven.plugin.logging.Log; -import org.codehaus.plexus.logging.Logger; - -/** - * This logger implements both types of logs currently in use. It can be injected where needed - * to turn off logs during testing where they aren't desired. - * - * @author Brian Fox - */ -public class SilentLog implements Log, Logger { - /** - * @return false - * @see org.apache.maven.plugin.logging.Log#isDebugEnabled() - */ - @Override - public boolean isDebugEnabled() { - return false; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#debug(java.lang.CharSequence) - */ - @Override - public void debug(CharSequence content) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#debug(java.lang.CharSequence, java.lang.Throwable) - */ - @Override - public void debug(CharSequence content, Throwable error) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#debug(java.lang.Throwable) - */ - @Override - public void debug(Throwable error) { - // nop - } - - /** - * @return false - * @see org.apache.maven.plugin.logging.Log#isInfoEnabled() - */ - @Override - public boolean isInfoEnabled() { - return false; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#info(java.lang.CharSequence) - */ - @Override - public void info(CharSequence content) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#info(java.lang.CharSequence, java.lang.Throwable) - */ - @Override - public void info(CharSequence content, Throwable error) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#info(java.lang.Throwable) - */ - @Override - public void info(Throwable error) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#isWarnEnabled() - */ - @Override - public boolean isWarnEnabled() { - // nop - return false; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#warn(java.lang.CharSequence) - */ - @Override - public void warn(CharSequence content) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#warn(java.lang.CharSequence, java.lang.Throwable) - */ - @Override - public void warn(CharSequence content, Throwable error) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#warn(java.lang.Throwable) - */ - @Override - public void warn(Throwable error) { - // nop - } - - /** - * @return false - * @see org.apache.maven.plugin.logging.Log#isErrorEnabled() - */ - @Override - public boolean isErrorEnabled() { - return false; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#error(java.lang.CharSequence) - */ - @Override - public void error(CharSequence content) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#error(java.lang.CharSequence, java.lang.Throwable) - */ - @Override - public void error(CharSequence content, Throwable error) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.plugin.logging.Log#error(java.lang.Throwable) - */ - @Override - public void error(Throwable error) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#debug(java.lang.String) - */ - @Override - public void debug(String message) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#debug(java.lang.String, java.lang.Throwable) - */ - @Override - public void debug(String message, Throwable throwable) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#info(java.lang.String) - */ - @Override - public void info(String message) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#info(java.lang.String, java.lang.Throwable) - */ - @Override - public void info(String message, Throwable throwable) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#warn(java.lang.String) - */ - @Override - public void warn(String message) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#warn(java.lang.String, java.lang.Throwable) - */ - @Override - public void warn(String message, Throwable throwable) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#error(java.lang.String) - */ - @Override - public void error(String message) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#error(java.lang.String, java.lang.Throwable) - */ - @Override - public void error(String message, Throwable throwable) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#fatalError(java.lang.String) - */ - @Override - public void fatalError(String message) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.codehaus.plexus.logging.Logger#fatalError(java.lang.String, java.lang.Throwable) - */ - @Override - public void fatalError(String message, Throwable throwable) { - // nop - } - - /** - * @return false - * @see org.codehaus.plexus.logging.Logger#isFatalErrorEnabled() - */ - @Override - public boolean isFatalErrorEnabled() { - return false; - } - - /** - * @return null - * @see org.codehaus.plexus.logging.Logger#getChildLogger(java.lang.String) - */ - @Override - public Logger getChildLogger(String name) { - return null; - } - - /** - * @return 0 - * @see org.codehaus.plexus.logging.Logger#getThreshold() - */ - @Override - public int getThreshold() { - return 0; - } - - /** - * @return null - * @see org.codehaus.plexus.logging.Logger#getName() - */ - @Override - public String getName() { - return null; - } - - @Override - public void setThreshold(int threshold) { - // TODO Auto-generated method stub - - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/WithoutMojo.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/WithoutMojo.java deleted file mode 100644 index 4fa6bbf..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/WithoutMojo.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.plugin.testing; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * - * An annotation for test methods that do not require the {@link MojoRule} to create and tear down the instance. - * - * @author Mirko Friedenhagen - */ -@Retention(RUNTIME) -@Documented -@Target(METHOD) -public @interface WithoutMojo {} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/InjectMojo.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/InjectMojo.java deleted file mode 100644 index 7b2fbdc..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/InjectMojo.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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.plugin.testing.junit5; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * - */ -@Retention(RetentionPolicy.RUNTIME) -public @interface InjectMojo { - - String goal(); - - String pom(); - - boolean empty() default false; -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoExtension.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoExtension.java deleted file mode 100644 index c7746c2..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoExtension.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * 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.plugin.testing.junit5; - -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Field; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import com.google.inject.internal.ProviderMethodsModule; -import org.apache.maven.api.plugin.testing.MojoTest; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.lifecycle.internal.MojoDescriptorCreator; -import org.apache.maven.plugin.Mojo; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.plugin.PluginParameterExpressionEvaluator; -import org.apache.maven.plugin.descriptor.MojoDescriptor; -import org.apache.maven.plugin.descriptor.Parameter; -import org.apache.maven.plugin.descriptor.PluginDescriptor; -import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugin.testing.ConfigurationException; -import org.apache.maven.plugin.testing.MojoLogWrapper; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.DefaultPlexusContainer; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.component.configurator.BasicComponentConfigurator; -import org.codehaus.plexus.component.configurator.ComponentConfigurator; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; -import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; -import org.codehaus.plexus.testing.PlexusExtension; -import org.codehaus.plexus.util.InterpolationFilterReader; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.ReflectionUtils; -import org.codehaus.plexus.util.xml.XmlStreamReader; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.ParameterContext; -import org.junit.jupiter.api.extension.ParameterResolutionException; -import org.junit.jupiter.api.extension.ParameterResolver; -import org.mockito.Mockito; -import org.slf4j.LoggerFactory; - -/** - * JUnit extension to help testing Mojos. The extension should be automatically registered - * by adding the {@link org.apache.maven.api.plugin.testing.MojoTest} annotation on the test class. - * - * @see MojoTest - * @see org.apache.maven.api.plugin.testing.InjectMojo - * @see org.apache.maven.api.plugin.testing.MojoParameter - */ -public class MojoExtension extends PlexusExtension implements ParameterResolver { - - @Override - public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { - return parameterContext.isAnnotated(InjectMojo.class) - || parameterContext.getDeclaringExecutable().isAnnotationPresent(InjectMojo.class); - } - - @Override - public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { - try { - InjectMojo injectMojo = parameterContext - .findAnnotation(InjectMojo.class) - .orElseGet(() -> parameterContext.getDeclaringExecutable().getAnnotation(InjectMojo.class)); - - Set mojoParameters = - new HashSet<>(parameterContext.findRepeatableAnnotations(MojoParameter.class)); - - Optional.ofNullable(parameterContext.getDeclaringExecutable().getAnnotation(MojoParameter.class)) - .ifPresent(mojoParameters::add); - - Optional.ofNullable(parameterContext.getDeclaringExecutable().getAnnotation(MojoParameters.class)) - .map(MojoParameters::value) - .map(Arrays::asList) - .ifPresent(mojoParameters::addAll); - - Class holder = parameterContext.getTarget().get().getClass(); - PluginDescriptor descriptor = extensionContext - .getStore(ExtensionContext.Namespace.GLOBAL) - .get(PluginDescriptor.class, PluginDescriptor.class); - return lookupMojo(holder, injectMojo, mojoParameters, descriptor); - } catch (Exception e) { - throw new ParameterResolutionException("Unable to resolve parameter", e); - } - } - - @Override - public void beforeEach(ExtensionContext context) throws Exception { - // TODO provide protected setters in PlexusExtension - Field field = PlexusExtension.class.getDeclaredField("basedir"); - field.setAccessible(true); - field.set(null, getBasedir()); - field = PlexusExtension.class.getDeclaredField("context"); - field.setAccessible(true); - field.set(this, context); - - getContainer().addComponent(getContainer(), PlexusContainer.class.getName()); - - ((DefaultPlexusContainer) getContainer()).addPlexusInjector(Collections.emptyList(), binder -> { - binder.install(ProviderMethodsModule.forObject(context.getRequiredTestInstance())); - binder.requestInjection(context.getRequiredTestInstance()); - binder.bind(Log.class).toInstance(new MojoLogWrapper(LoggerFactory.getLogger("anonymous"))); - binder.bind(MavenSession.class).toInstance(mockMavenSession()); - binder.bind(MojoExecution.class).toInstance(mockMojoExecution()); - }); - - Map map = getContainer().getContext().getContextData(); - - ClassLoader classLoader = context.getRequiredTestClass().getClassLoader(); - try (InputStream is = Objects.requireNonNull( - classLoader.getResourceAsStream(getPluginDescriptorLocation()), - "Unable to find plugin descriptor: " + getPluginDescriptorLocation()); - Reader reader = new BufferedReader(new XmlStreamReader(is)); - InterpolationFilterReader interpolationReader = new InterpolationFilterReader(reader, map, "${", "}")) { - - PluginDescriptor pluginDescriptor = new PluginDescriptorBuilder().build(interpolationReader); - - context.getStore(ExtensionContext.Namespace.GLOBAL).put(PluginDescriptor.class, pluginDescriptor); - - for (ComponentDescriptor desc : pluginDescriptor.getComponents()) { - getContainer().addComponentDescriptor(desc); - } - } - } - - /** - * Default MojoExecution mock - * - * @return a MojoExecution mock - */ - private MojoExecution mockMojoExecution() { - return Mockito.mock(MojoExecution.class); - } - - /** - * Default MavenSession mock - * - * @return a MavenSession mock - */ - private MavenSession mockMavenSession() { - MavenSession session = Mockito.mock(MavenSession.class); - Mockito.when(session.getUserProperties()).thenReturn(new Properties()); - Mockito.when(session.getSystemProperties()).thenReturn(new Properties()); - return session; - } - - protected String getPluginDescriptorLocation() { - return "META-INF/maven/plugin.xml"; - } - - private Mojo lookupMojo( - Class holder, - InjectMojo injectMojo, - Collection mojoParameters, - PluginDescriptor descriptor) - throws Exception { - String goal = injectMojo.goal(); - String pom = injectMojo.pom(); - String[] coord = mojoCoordinates(goal); - Xpp3Dom pomDom; - if (pom.startsWith("file:")) { - Path path = Paths.get(getBasedir()).resolve(pom.substring("file:".length())); - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(path.toFile())); - } else if (pom.startsWith("classpath:")) { - URL url = holder.getResource(pom.substring("classpath:".length())); - if (url == null) { - throw new IllegalStateException("Unable to find pom on classpath: " + pom); - } - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(url.openStream())); - } else if (pom.contains("")) { - pomDom = Xpp3DomBuilder.build(new StringReader(pom)); - } else { - Path path = Paths.get(getBasedir()).resolve(pom); - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(path.toFile())); - } - Xpp3Dom pluginConfiguration = extractPluginConfiguration(coord[1], pomDom); - if (!mojoParameters.isEmpty()) { - List children = mojoParameters.stream() - .map(mp -> { - Xpp3Dom c = new Xpp3Dom(mp.name()); - c.setValue(mp.value()); - return c; - }) - .collect(Collectors.toList()); - Xpp3Dom config = new Xpp3Dom("configuration"); - children.forEach(config::addChild); - pluginConfiguration = Xpp3Dom.mergeXpp3Dom(config, pluginConfiguration); - } - Mojo mojo = lookupMojo(coord, pluginConfiguration, descriptor); - return mojo; - } - - protected String[] mojoCoordinates(String goal) throws Exception { - if (goal.matches(".*:.*:.*:.*")) { - return goal.split(":"); - } else { - Path pluginPom = Paths.get(getBasedir(), "pom.xml"); - Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(pluginPom.toFile())); - String artifactId = pluginPomDom.getChild("artifactId").getValue(); - String groupId = resolveFromRootThenParent(pluginPomDom, "groupId"); - String version = resolveFromRootThenParent(pluginPomDom, "version"); - return new String[] {groupId, artifactId, version, goal}; - } - } - - /** - * lookup the mojo while we have all the relevent information - */ - protected Mojo lookupMojo(String[] coord, Xpp3Dom pluginConfiguration, PluginDescriptor descriptor) - throws Exception { - // pluginkey = groupId : artifactId : version : goal - Mojo mojo = lookup(Mojo.class, coord[0] + ":" + coord[1] + ":" + coord[2] + ":" + coord[3]); - for (MojoDescriptor mojoDescriptor : descriptor.getMojos()) { - if (Objects.equals( - mojoDescriptor.getImplementation(), mojo.getClass().getName())) { - if (pluginConfiguration != null) { - pluginConfiguration = finalizeConfig(pluginConfiguration, mojoDescriptor); - } - } - } - if (pluginConfiguration != null) { - MavenSession session = getContainer().lookup(MavenSession.class); - MavenProject project; - try { - project = getContainer().lookup(MavenProject.class); - } catch (ComponentLookupException e) { - project = null; - } - MojoExecution mojoExecution; - try { - mojoExecution = getContainer().lookup(MojoExecution.class); - } catch (ComponentLookupException e) { - mojoExecution = null; - } - ExpressionEvaluator evaluator = - new WrapEvaluator(getContainer(), new PluginParameterExpressionEvaluator(session, mojoExecution)); - ComponentConfigurator configurator = new BasicComponentConfigurator(); - configurator.configureComponent( - mojo, - new XmlPlexusConfiguration(pluginConfiguration), - evaluator, - getContainer().getContainerRealm()); - } - - mojo.setLog(getContainer().lookup(Log.class)); - - return mojo; - } - - private Xpp3Dom finalizeConfig(Xpp3Dom config, MojoDescriptor mojoDescriptor) { - List children = new ArrayList<>(); - if (mojoDescriptor != null && mojoDescriptor.getParameters() != null) { - Xpp3Dom defaultConfiguration = MojoDescriptorCreator.convert(mojoDescriptor); - for (Parameter parameter : mojoDescriptor.getParameters()) { - Xpp3Dom parameterConfiguration = config.getChild(parameter.getName()); - if (parameterConfiguration == null) { - parameterConfiguration = config.getChild(parameter.getAlias()); - } - Xpp3Dom parameterDefaults = defaultConfiguration.getChild(parameter.getName()); - parameterConfiguration = Xpp3Dom.mergeXpp3Dom(parameterConfiguration, parameterDefaults, Boolean.TRUE); - if (parameterConfiguration != null) { - if (isEmpty(parameterConfiguration.getAttribute("implementation")) - && !isEmpty(parameter.getImplementation())) { - parameterConfiguration.setAttribute("implementation", parameter.getImplementation()); - } - children.add(parameterConfiguration); - } - } - } - Xpp3Dom c = new Xpp3Dom("configuration"); - children.forEach(c::addChild); - return c; - } - - private boolean isEmpty(String str) { - return str == null || str.isEmpty(); - } - - private static Optional child(Xpp3Dom element, String name) { - return Optional.ofNullable(element.getChild(name)); - } - - private static Stream children(Xpp3Dom element) { - return Stream.of(element.getChildren()); - } - - public static Xpp3Dom extractPluginConfiguration(String artifactId, Xpp3Dom pomDom) throws Exception { - Xpp3Dom pluginConfigurationElement = child(pomDom, "build") - .flatMap(buildElement -> child(buildElement, "plugins")) - .map(MojoExtension::children) - .orElseGet(Stream::empty) - .filter(e -> e.getChild("artifactId").getValue().equals(artifactId)) - .findFirst() - .flatMap(buildElement -> child(buildElement, "configuration")) - .orElseThrow( - () -> new ConfigurationException("Cannot find a configuration element for a plugin with an " - + "artifactId of " + artifactId + ".")); - return pluginConfigurationElement; - } - - /** - * sometimes the parent element might contain the correct value so generalize that access - * - * TODO find out where this is probably done elsewhere - */ - private static String resolveFromRootThenParent(Xpp3Dom pluginPomDom, String element) throws Exception { - return Optional.ofNullable(child(pluginPomDom, element).orElseGet(() -> child(pluginPomDom, "parent") - .flatMap(e -> child(e, element)) - .orElse(null))) - .map(Xpp3Dom::getValue) - .orElseThrow(() -> new Exception("unable to determine " + element)); - } - - /** - * Convenience method to obtain the value of a variable on a mojo that might not have a getter. - *
- * Note: the caller is responsible for casting to what the desired type is. - */ - public static Object getVariableValueFromObject(Object object, String variable) throws IllegalAccessException { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); - field.setAccessible(true); - return field.get(object); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - *
- * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - */ - public static Map getVariablesAndValuesFromObject(Object object) throws IllegalAccessException { - return getVariablesAndValuesFromObject(object.getClass(), object); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - *
- * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - * - * @return map of variable names and values - */ - public static Map getVariablesAndValuesFromObject(Class clazz, Object object) - throws IllegalAccessException { - Map map = new HashMap<>(); - Field[] fields = clazz.getDeclaredFields(); - AccessibleObject.setAccessible(fields, true); - for (Field field : fields) { - map.put(field.getName(), field.get(object)); - } - Class superclass = clazz.getSuperclass(); - if (!Object.class.equals(superclass)) { - map.putAll(getVariablesAndValuesFromObject(superclass, object)); - } - return map; - } - - /** - * Convenience method to set values to variables in objects that don't have setters - */ - public static void setVariableValueToObject(Object object, String variable, Object value) - throws IllegalAccessException { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); - Objects.requireNonNull(field, "Field " + variable + " not found"); - field.setAccessible(true); - field.set(object, value); - } - - static class WrapEvaluator implements TypeAwareExpressionEvaluator { - - private final PlexusContainer container; - private final TypeAwareExpressionEvaluator evaluator; - - WrapEvaluator(PlexusContainer container, TypeAwareExpressionEvaluator evaluator) { - this.container = container; - this.evaluator = evaluator; - } - - @Override - public Object evaluate(String expression) throws ExpressionEvaluationException { - return evaluate(expression, null); - } - - @Override - public Object evaluate(String expression, Class type) throws ExpressionEvaluationException { - Object value = evaluator.evaluate(expression, type); - if (value == null) { - String expr = stripTokens(expression); - if (expr != null) { - try { - value = container.lookup(type, expr); - } catch (ComponentLookupException e) { - // nothing - } - } - } - return value; - } - - private String stripTokens(String expr) { - if (expr.startsWith("${") && expr.endsWith("}")) { - return expr.substring(2, expr.length() - 1); - } - return null; - } - - @Override - public File alignToBaseDirectory(File path) { - return evaluator.alignToBaseDirectory(path); - } - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoParameter.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoParameter.java deleted file mode 100644 index a3a8294..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoParameter.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.plugin.testing.junit5; - -import java.lang.annotation.Repeatable; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Mojo parameter - */ -@Retention(RetentionPolicy.RUNTIME) -@Repeatable(MojoParameters.class) -public @interface MojoParameter { - String name(); - - String value(); -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/resources/TestResources.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/resources/TestResources.java deleted file mode 100644 index 54343f1..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/resources/TestResources.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * 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.plugin.testing.resources; - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.Set; -import java.util.TreeSet; - -import org.codehaus.plexus.util.DirectoryScanner; -import org.codehaus.plexus.util.FileUtils; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.rules.TestWatcher; -import org.junit.runner.Description; - -/** - * Junit4 test {@link Rule} to extract and assert test resources. - * - * @since 3.1.0 - */ -public class TestResources extends TestWatcher { - - private final String projectsDir; - - private final String workDir; - - public TestResources() { - this("src/test/projects", "target/test-projects"); - } - - public TestResources(String projectsDir, String workDir) { - this.projectsDir = projectsDir; - this.workDir = workDir; - } - - private String name; - - @Override - protected void starting(Description d) { - String methodName = d.getMethodName(); - if (methodName != null) { - methodName = methodName.replace('/', '_').replace('\\', '_'); - } - name = d.getTestClass().getSimpleName() + "_" + methodName; - } - - /** - * Creates new clean copy of test project directory structure. The copy is named after both the test being executed - * and test project name, which allows the same test project can be used by multiple tests and by different - * instances of the same parametrized tests. - *

- * TODO Provide alternative working directory naming for Windows, which still limits path names to ~250 charecters - */ - public File getBasedir(String project) throws IOException { - if (name == null) { - throw new IllegalStateException( - getClass().getSimpleName() + " must be a test class field annotated with org.junit.Rule"); - } - File src = new File(projectsDir, project).getCanonicalFile(); - Assert.assertTrue("Test project directory does not exist: " + src.getPath(), src.isDirectory()); - File basedir = new File(workDir, name + "_" + project).getCanonicalFile(); - FileUtils.deleteDirectory(basedir); - Assert.assertTrue("Test project working directory created", basedir.mkdirs()); - FileUtils.copyDirectoryStructure(src, basedir); - return basedir; - } - - // static helpers - - public static void cp(File basedir, String from, String to) throws IOException { - // TODO ensure destination lastModified timestamp changes - FileUtils.copyFile(new File(basedir, from), new File(basedir, to)); - } - - public static void assertFileContents(File basedir, String expectedPath, String actualPath) throws IOException { - String expected = FileUtils.fileRead(new File(basedir, expectedPath)); - String actual = FileUtils.fileRead(new File(basedir, actualPath)); - Assert.assertEquals(expected, actual); - } - - public static void assertDirectoryContents(File dir, String... expectedPaths) { - DirectoryScanner scanner = new DirectoryScanner(); - scanner.setBasedir(dir); - scanner.addDefaultExcludes(); - scanner.scan(); - - Set actual = new TreeSet<>(); - for (String path : scanner.getIncludedFiles()) { - actual.add(path); - } - for (String path : scanner.getIncludedDirectories()) { - if (path.length() > 0) { - actual.add(path + "/"); - } - } - - Set expected = new TreeSet<>(); - if (expectedPaths != null) { - for (String path : expectedPaths) { - expected.add(path); - } - } - - // compare textual representation to make diff easier to understand - Assert.assertEquals(toString(expected), toString(actual)); - } - - private static String toString(Collection strings) { - StringBuilder sb = new StringBuilder(); - for (String string : strings) { - sb.append(string).append('\n'); - } - return sb.toString(); - } - - public static void touch(File basedir, String path) throws InterruptedException { - touch(new File(basedir, path)); - } - - public static void touch(File file) throws InterruptedException { - if (!file.isFile()) { - throw new IllegalArgumentException("Not a file " + file); - } - long lastModified = file.lastModified(); - file.setLastModified(System.currentTimeMillis()); - - // TODO do modern filesystems still have this silly lastModified resolution? - if (lastModified == file.lastModified()) { - Thread.sleep(1000L); - file.setLastModified(System.currentTimeMillis()); - } - } - - public static void rm(File basedir, String path) { - Assert.assertTrue("delete " + path, new File(basedir, path).delete()); - } - - /** - * @since 3.2.0 - */ - public static void create(File basedir, String... paths) throws IOException { - if (paths == null || paths.length == 0) { - throw new IllegalArgumentException(); - } - for (String path : paths) { - File file = new File(basedir, path); - Assert.assertTrue(file.getParentFile().mkdirs()); - file.createNewFile(); - Assert.assertTrue(file.isFile() && file.canRead()); - } - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/ArtifactStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/ArtifactStub.java deleted file mode 100644 index edbaa9e..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/ArtifactStub.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * 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.plugin.testing.stubs; - -import java.io.File; -import java.util.Collection; -import java.util.List; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.handler.ArtifactHandler; -import org.apache.maven.artifact.metadata.ArtifactMetadata; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.resolver.filter.ArtifactFilter; -import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.apache.maven.artifact.versioning.OverConstrainedVersionException; -import org.apache.maven.artifact.versioning.VersionRange; - -/** - * Stub class for {@link Artifact} testing. - * - * @author jesse - */ -public class ArtifactStub implements Artifact { - private String groupId; - - private String artifactId; - - private String version; - - private String scope; - - private String type; - - private String classifier; - - private File file; - - private ArtifactRepository artifactRepository; - - /** - * By default, return 0 - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(Artifact artifact) { - return 0; - } - - /** {@inheritDoc} */ - @Override - public String getGroupId() { - return groupId; - } - - /** {@inheritDoc} */ - @Override - public String getArtifactId() { - return artifactId; - } - - /** {@inheritDoc} */ - @Override - public String getVersion() { - return version; - } - - /** {@inheritDoc} */ - @Override - public void setVersion(String version) { - this.version = version; - } - - /** {@inheritDoc} */ - @Override - public String getScope() { - return scope; - } - - /** {@inheritDoc} */ - @Override - public String getType() { - return type; - } - - /** - * Set a new type - * - * @param type - */ - public void setType(String type) { - this.type = type; - } - - /** {@inheritDoc} */ - @Override - public String getClassifier() { - return classifier; - } - - /** {@inheritDoc} */ - @Override - public boolean hasClassifier() { - return classifier != null; - } - - /** {@inheritDoc} */ - @Override - public File getFile() { - return file; - } - - /** {@inheritDoc} */ - @Override - public void setFile(File file) { - this.file = file; - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getBaseVersion() - */ - @Override - public String getBaseVersion() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setBaseVersion(java.lang.String) - */ - @Override - public void setBaseVersion(String string) { - // nop - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getId() - */ - @Override - public String getId() { - return null; - } - - /** - * @return groupId:artifactId:type:classifier. - * @see org.apache.maven.artifact.Artifact#getDependencyConflictId() - */ - @Override - public String getDependencyConflictId() { - StringBuffer buffer = new StringBuffer(); - - buffer.append(getGroupId()); - buffer.append(":").append(getArtifactId()); - buffer.append(":").append(getType()); - buffer.append(":").append(getClassifier()); - - return buffer.toString(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#addMetadata(org.apache.maven.artifact.metadata.ArtifactMetadata) - */ - @Override - public void addMetadata(ArtifactMetadata artifactMetadata) { - // nop - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getMetadataList() - */ - @Override - public Collection getMetadataList() { - return null; - } - - /** {@inheritDoc} */ - @Override - public void setRepository(ArtifactRepository artifactRepository) { - this.artifactRepository = artifactRepository; - } - - /** {@inheritDoc} */ - @Override - public ArtifactRepository getRepository() { - return artifactRepository; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#updateVersion(java.lang.String, org.apache.maven.artifact.repository.ArtifactRepository) - */ - @Override - public void updateVersion(String string, ArtifactRepository artifactRepository) { - // nop - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getDownloadUrl() - */ - @Override - public String getDownloadUrl() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setDownloadUrl(java.lang.String) - */ - @Override - public void setDownloadUrl(String string) { - // nop - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getDependencyFilter() - */ - @Override - public ArtifactFilter getDependencyFilter() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setDependencyFilter(org.apache.maven.artifact.resolver.filter.ArtifactFilter) - */ - @Override - public void setDependencyFilter(ArtifactFilter artifactFilter) { - // nop - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getArtifactHandler() - */ - @Override - public ArtifactHandler getArtifactHandler() { - return null; - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getDependencyTrail() - */ - @Override - public List getDependencyTrail() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setDependencyTrail(java.util.List) - */ - @Override - public void setDependencyTrail(List list) { - // nop - } - - /** {@inheritDoc} */ - @Override - public void setScope(String scope) { - this.scope = scope; - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getVersionRange() - */ - @Override - public VersionRange getVersionRange() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setVersionRange(org.apache.maven.artifact.versioning.VersionRange) - */ - @Override - public void setVersionRange(VersionRange versionRange) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#selectVersion(java.lang.String) - */ - @Override - public void selectVersion(String string) { - // nop - } - - /** {@inheritDoc} */ - @Override - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - /** {@inheritDoc} */ - @Override - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } - - /** - * @return false. - * @see org.apache.maven.artifact.Artifact#isSnapshot() - */ - @Override - public boolean isSnapshot() { - return Artifact.VERSION_FILE_PATTERN.matcher(getVersion()).matches() - || getVersion().endsWith(Artifact.SNAPSHOT_VERSION); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setResolved(boolean) - */ - @Override - public void setResolved(boolean b) { - // nop - } - - /** - * @return false. - * @see org.apache.maven.artifact.Artifact#isResolved() - */ - @Override - public boolean isResolved() { - return false; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setResolvedVersion(java.lang.String) - */ - @Override - public void setResolvedVersion(String string) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setArtifactHandler(org.apache.maven.artifact.handler.ArtifactHandler) - */ - @Override - public void setArtifactHandler(ArtifactHandler artifactHandler) { - // nop - } - - /** - * @return false. - * @see org.apache.maven.artifact.Artifact#isRelease() - */ - @Override - public boolean isRelease() { - return !isSnapshot(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setRelease(boolean) - */ - @Override - public void setRelease(boolean b) { - // nop - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getAvailableVersions() - */ - @Override - public List getAvailableVersions() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.Artifact#setAvailableVersions(java.util.List) - */ - @Override - public void setAvailableVersions(List list) { - // nop - } - - /** - * @return false. - * @see org.apache.maven.artifact.Artifact#isOptional() - */ - @Override - public boolean isOptional() { - return false; - } - - /** - * By default, do nothing. - * - * @param b - */ - @Override - public void setOptional(boolean b) { - // nop - } - - /** - * @return null. - * @see org.apache.maven.artifact.Artifact#getSelectedVersion() - */ - @Override - public ArtifactVersion getSelectedVersion() throws OverConstrainedVersionException { - return null; - } - - /** - * @return false. - * @see org.apache.maven.artifact.Artifact#isSelectedVersionKnown() - */ - @Override - public boolean isSelectedVersionKnown() throws OverConstrainedVersionException { - return false; - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - if (getGroupId() != null) { - sb.append(getGroupId()); - sb.append(":"); - } - appendArtifactTypeClassifierString(sb); - if (version != null) { - sb.append(":"); - sb.append(getVersion()); - } - if (scope != null) { - sb.append(":"); - sb.append(scope); - } - return sb.toString(); - } - - private void appendArtifactTypeClassifierString(StringBuffer sb) { - sb.append(getArtifactId()); - sb.append(":"); - sb.append(getType()); - if (hasClassifier()) { - sb.append(":"); - sb.append(getClassifier()); - } - } - - public boolean isFromAuthoritativeRepository() { - return true; - } - - public void setFromAuthoritativeRepository(boolean fromAuthoritativeRepository) { - // nothing - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/DefaultArtifactHandlerStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/DefaultArtifactHandlerStub.java deleted file mode 100644 index 5c5fe7a..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/DefaultArtifactHandlerStub.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * 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.plugin.testing.stubs; - -import org.apache.maven.artifact.handler.ArtifactHandler; - -/** - * Minimal artifact handler used by the stub factory to create unpackable archives. - * - * @author Brian Fox - */ -public class DefaultArtifactHandlerStub implements ArtifactHandler { - private String extension; - - private String type; - - private String classifier; - - private String directory; - - private String packaging; - - private boolean includesDependencies; - - private String language; - - private boolean addedToClasspath; - - /** - * @param t the artifact handler type - * @param c the artifact handler classifier - */ - public DefaultArtifactHandlerStub(String t, String c) { - type = t; - classifier = c; - if (t.equals("test-jar")) { - extension = "jar"; - } - } - - /** - * @param type the artifact handler type - */ - public DefaultArtifactHandlerStub(String type) { - this.type = type; - } - - /** {@inheritDoc} */ - @Override - public String getExtension() { - if (extension == null) { - extension = type; - } - return extension; - } - - /** - * @return the artifact handler type - */ - public String getType() { - return type; - } - - /** {@inheritDoc} */ - @Override - public String getClassifier() { - return classifier; - } - - /** {@inheritDoc} */ - @Override - public String getDirectory() { - if (directory == null) { - directory = getPackaging() + "s"; - } - return directory; - } - - /** {@inheritDoc} */ - @Override - public String getPackaging() { - if (packaging == null) { - packaging = getType(); - } - return packaging; - } - - /** {@inheritDoc} */ - @Override - public boolean isIncludesDependencies() { - return includesDependencies; - } - - /** {@inheritDoc} */ - @Override - public String getLanguage() { - if (language == null) { - language = "none"; - } - - return language; - } - - /** {@inheritDoc} */ - @Override - public boolean isAddedToClasspath() { - return addedToClasspath; - } - - /** - * @param theAddedToClasspath The addedToClasspath to set. - */ - public void setAddedToClasspath(boolean theAddedToClasspath) { - this.addedToClasspath = theAddedToClasspath; - } - - /** - * @param theClassifier The classifier to set. - */ - public void setClassifier(String theClassifier) { - this.classifier = theClassifier; - } - - /** - * @param theDirectory The directory to set. - */ - public void setDirectory(String theDirectory) { - this.directory = theDirectory; - } - - /** - * @param theExtension The extension to set. - */ - public void setExtension(String theExtension) { - this.extension = theExtension; - } - - /** - * @param theIncludesDependencies The includesDependencies to set. - */ - public void setIncludesDependencies(boolean theIncludesDependencies) { - this.includesDependencies = theIncludesDependencies; - } - - /** - * @param theLanguage The language to set. - */ - public void setLanguage(String theLanguage) { - this.language = theLanguage; - } - - /** - * @param thePackaging The packaging to set. - */ - public void setPackaging(String thePackaging) { - this.packaging = thePackaging; - } - - /** - * @param theType The type to set. - */ - public void setType(String theType) { - this.type = theType; - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/MavenProjectStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/MavenProjectStub.java deleted file mode 100644 index 513629b..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/MavenProjectStub.java +++ /dev/null @@ -1,1487 +0,0 @@ -/* - * 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.plugin.testing.stubs; - -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.resolver.filter.ArtifactFilter; -import org.apache.maven.model.Build; -import org.apache.maven.model.CiManagement; -import org.apache.maven.model.Contributor; -import org.apache.maven.model.Dependency; -import org.apache.maven.model.DependencyManagement; -import org.apache.maven.model.Developer; -import org.apache.maven.model.DistributionManagement; -import org.apache.maven.model.Extension; -import org.apache.maven.model.IssueManagement; -import org.apache.maven.model.License; -import org.apache.maven.model.MailingList; -import org.apache.maven.model.Model; -import org.apache.maven.model.Organization; -import org.apache.maven.model.Plugin; -import org.apache.maven.model.PluginManagement; -import org.apache.maven.model.Prerequisites; -import org.apache.maven.model.Profile; -import org.apache.maven.model.ReportPlugin; -import org.apache.maven.model.Reporting; -import org.apache.maven.model.Repository; -import org.apache.maven.model.Resource; -import org.apache.maven.model.Scm; -import org.apache.maven.model.io.xpp3.MavenXpp3Reader; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; - -/** - * Very simple stub of MavenProject object, going to take a lot of work to make it - * useful as a stub though. - * - * @author jesse - */ -public class MavenProjectStub extends MavenProject { - private String groupId; - - private String artifactId; - - private String name; - - private Model model; - - private MavenProject parent; - - private File file; - - private List collectedProjects; - - private List attachedArtifacts; - - private List compileSourceRoots; - - private List testCompileSourceRoots; - - private List scriptSourceRoots; - - private List pluginArtifactRepositories; - - private ArtifactRepository releaseArtifactRepository; - - private ArtifactRepository snapshotArtifactRepository; - - private List activeProfiles; - - private Set dependencyArtifacts; - - private Artifact artifact; - - private Map artifactMap; - - private Model originalModel; - - private Map pluginArtifactMap; - - private Map reportArtifactMap; - - private Map extensionArtifactMap; - - private Map projectReferences; - - private Build buildOverlay; - - private boolean executionRoot; - - private List compileArtifacts; - - private List compileDependencies; - - private List systemDependencies; - - private List testClasspathElements; - - private List testDependencies; - - private List systemClasspathElements; - - private List systemArtifacts; - - private List testArtifacts; - - private List runtimeArtifacts; - - private List runtimeDependencies; - - private List runtimeClasspathElements; - - private String modelVersion; - - private String packaging; - - private String inceptionYear; - - private String url; - - private String description; - - private String version; - - private String defaultGoal; - - private List licenses; - - private Build build; - - /** - * Default constructor - */ - public MavenProjectStub() { - this(new Model()); - } - - /** - * @param model the given model - */ - public MavenProjectStub(Model model) { - super((Model) null); - this.model = model; - } - - /** - * Loads the model for this stub from the specified POM. For convenience, any checked exception caused by I/O or - * parser errors will be wrapped into an unchecked exception. - * - * @param pomFile The path to the POM file to load, must not be null. If this path is relative, it - * is resolved against the return value of {@link #getBasedir()}. - */ - protected void readModel(File pomFile) { - if (!pomFile.isAbsolute()) { - pomFile = new File(getBasedir(), pomFile.getPath()); - } - try { - setModel(new MavenXpp3Reader().read(ReaderFactory.newXmlReader(pomFile))); - } catch (IOException e) { - throw new RuntimeException("Failed to read POM file: " + pomFile, e); - } catch (XmlPullParserException e) { - throw new RuntimeException("Failed to parse POM file: " + pomFile, e); - } - } - - /** - * No project model is associated - * - * @param project the given project - */ - public MavenProjectStub(MavenProject project) { - super((Model) null); - } - - /** - * @param mavenProject - * @return an empty String - * @throws IOException if any - */ - @Override - public String getModulePathAdjustment(MavenProject mavenProject) throws IOException { - return ""; - } - - /** {@inheritDoc} */ - @Override - public Artifact getArtifact() { - return artifact; - } - - /** {@inheritDoc} */ - @Override - public void setArtifact(Artifact artifact) { - this.artifact = artifact; - } - - /** {@inheritDoc} */ - @Override - public Model getModel() { - return model; - } - - /** {@inheritDoc} */ - @Override - public MavenProject getParent() { - return parent; - } - - /** {@inheritDoc} */ - @Override - public void setParent(MavenProject mavenProject) { - this.parent = mavenProject; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setRemoteArtifactRepositories(java.util.List) - */ - @Override - public void setRemoteArtifactRepositories(List list) { - // nop - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getRemoteArtifactRepositories() - */ - @Override - public List getRemoteArtifactRepositories() { - return Collections.emptyList(); - } - - /** {@inheritDoc} */ - @Override - public boolean hasParent() { - if (parent != null) { - return true; - } - - return false; - } - - /** {@inheritDoc} */ - @Override - public File getFile() { - return file; - } - - /** {@inheritDoc} */ - @Override - public void setFile(File file) { - this.file = file; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() { - return new File(PlexusTestCase.getBasedir()); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setDependencies(java.util.List) - */ - @Override - public void setDependencies(List list) { - // nop - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getDependencies() - */ - @Override - public List getDependencies() { - return Collections.emptyList(); - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getDependencyManagement() - */ - @Override - public DependencyManagement getDependencyManagement() { - return null; - } - - /** {@inheritDoc} */ - @Override - public void addCompileSourceRoot(String string) { - if (compileSourceRoots == null) { - compileSourceRoots = new ArrayList<>(Collections.singletonList(string)); - } else { - compileSourceRoots.add(string); - } - } - - /** {@inheritDoc} */ - @Override - public void addScriptSourceRoot(String string) { - if (scriptSourceRoots == null) { - scriptSourceRoots = new ArrayList<>(Collections.singletonList(string)); - } else { - scriptSourceRoots.add(string); - } - } - - /** {@inheritDoc} */ - @Override - public void addTestCompileSourceRoot(String string) { - if (testCompileSourceRoots == null) { - testCompileSourceRoots = new ArrayList<>(Collections.singletonList(string)); - } else { - testCompileSourceRoots.add(string); - } - } - - /** {@inheritDoc} */ - @Override - public List getCompileSourceRoots() { - return compileSourceRoots; - } - - /** {@inheritDoc} */ - @Override - public List getScriptSourceRoots() { - return scriptSourceRoots; - } - - /** {@inheritDoc} */ - @Override - public List getTestCompileSourceRoots() { - return testCompileSourceRoots; - } - - /** {@inheritDoc} */ - @Override - public List getCompileClasspathElements() throws DependencyResolutionRequiredException { - return compileSourceRoots; - } - - /** - * @param compileArtifacts - */ - public void setCompileArtifacts(List compileArtifacts) { - this.compileArtifacts = compileArtifacts; - } - - /** {@inheritDoc} */ - @Override - public List getCompileArtifacts() { - return compileArtifacts; - } - - /** {@inheritDoc} */ - @Override - public List getCompileDependencies() { - return compileDependencies; - } - - /** {@inheritDoc} */ - @Override - public List getTestClasspathElements() throws DependencyResolutionRequiredException { - return testClasspathElements; - } - - /** {@inheritDoc} */ - @Override - public List getTestArtifacts() { - return testArtifacts; - } - - /** {@inheritDoc} */ - @Override - public List getTestDependencies() { - return testDependencies; - } - - /** {@inheritDoc} */ - @Override - public List getRuntimeClasspathElements() throws DependencyResolutionRequiredException { - return runtimeClasspathElements; - } - - /** {@inheritDoc} */ - @Override - public List getRuntimeArtifacts() { - return runtimeArtifacts; - } - - /** {@inheritDoc} */ - @Override - public List getRuntimeDependencies() { - return runtimeDependencies; - } - - /** {@inheritDoc} */ - @Override - public List getSystemClasspathElements() throws DependencyResolutionRequiredException { - return systemClasspathElements; - } - - /** {@inheritDoc} */ - @Override - public List getSystemArtifacts() { - return systemArtifacts; - } - - /** - * @param runtimeClasspathElements - */ - public void setRuntimeClasspathElements(List runtimeClasspathElements) { - this.runtimeClasspathElements = runtimeClasspathElements; - } - - /** - * @param attachedArtifacts - */ - @Override - public void setAttachedArtifacts(List attachedArtifacts) { - this.attachedArtifacts = attachedArtifacts; - } - - /** - * @param compileSourceRoots - */ - @Override - public void setCompileSourceRoots(List compileSourceRoots) { - this.compileSourceRoots = compileSourceRoots; - } - - /** - * @param testCompileSourceRoots - */ - @Override - public void setTestCompileSourceRoots(List testCompileSourceRoots) { - this.testCompileSourceRoots = testCompileSourceRoots; - } - - /** - * @param scriptSourceRoots - */ - @Override - public void setScriptSourceRoots(List scriptSourceRoots) { - this.scriptSourceRoots = scriptSourceRoots; - } - - /** - * @param artifactMap - */ - public void setArtifactMap(Map artifactMap) { - this.artifactMap = artifactMap; - } - - /** - * @param pluginArtifactMap - */ - public void setPluginArtifactMap(Map pluginArtifactMap) { - this.pluginArtifactMap = pluginArtifactMap; - } - - /** - * @param reportArtifactMap - */ - public void setReportArtifactMap(Map reportArtifactMap) { - this.reportArtifactMap = reportArtifactMap; - } - - /** - * @param extensionArtifactMap - */ - public void setExtensionArtifactMap(Map extensionArtifactMap) { - this.extensionArtifactMap = extensionArtifactMap; - } - - /** - * @param projectReferences - */ - public void setProjectReferences(Map projectReferences) { - this.projectReferences = projectReferences; - } - - /** - * @param buildOverlay - */ - public void setBuildOverlay(Build buildOverlay) { - this.buildOverlay = buildOverlay; - } - - /** - * @param compileDependencies - */ - public void setCompileDependencies(List compileDependencies) { - this.compileDependencies = compileDependencies; - } - - /** - * @param systemDependencies - */ - public void setSystemDependencies(List systemDependencies) { - this.systemDependencies = systemDependencies; - } - - /** - * @param testClasspathElements - */ - public void setTestClasspathElements(List testClasspathElements) { - this.testClasspathElements = testClasspathElements; - } - - /** - * @param testDependencies - */ - public void setTestDependencies(List testDependencies) { - this.testDependencies = testDependencies; - } - - /** - * @param systemClasspathElements - */ - public void setSystemClasspathElements(List systemClasspathElements) { - this.systemClasspathElements = systemClasspathElements; - } - - /** - * @param systemArtifacts - */ - public void setSystemArtifacts(List systemArtifacts) { - this.systemArtifacts = systemArtifacts; - } - - /** - * @param testArtifacts - */ - public void setTestArtifacts(List testArtifacts) { - this.testArtifacts = testArtifacts; - } - - /** - * @param runtimeArtifacts - */ - public void setRuntimeArtifacts(List runtimeArtifacts) { - this.runtimeArtifacts = runtimeArtifacts; - } - - /** - * @param runtimeDependencies - */ - public void setRuntimeDependencies(List runtimeDependencies) { - this.runtimeDependencies = runtimeDependencies; - } - - /** - * @param model - */ - @Override - public void setModel(Model model) { - this.model = model; - } - - /** {@inheritDoc} */ - @Override - public List getSystemDependencies() { - return systemDependencies; - } - - /** {@inheritDoc} */ - @Override - public void setModelVersion(String string) { - this.modelVersion = string; - } - - /** {@inheritDoc} */ - @Override - public String getModelVersion() { - return modelVersion; - } - - /** - * By default, return an empty String. - * - * @see org.apache.maven.project.MavenProject#getId() - */ - @Override - public String getId() { - return ""; - } - - /** {@inheritDoc} */ - @Override - public void setGroupId(String string) { - this.groupId = string; - } - - /** {@inheritDoc} */ - @Override - public String getGroupId() { - return groupId; - } - - /** {@inheritDoc} */ - @Override - public void setArtifactId(String string) { - this.artifactId = string; - } - - /** {@inheritDoc} */ - @Override - public String getArtifactId() { - return artifactId; - } - - /** {@inheritDoc} */ - @Override - public void setName(String string) { - this.name = string; - } - - /** {@inheritDoc} */ - @Override - public String getName() { - return name; - } - - /** {@inheritDoc} */ - @Override - public void setVersion(String string) { - this.version = string; - } - - /** {@inheritDoc} */ - @Override - public String getVersion() { - return version; - } - - /** {@inheritDoc} */ - @Override - public String getPackaging() { - return packaging; - } - - /** {@inheritDoc} */ - @Override - public void setPackaging(String string) { - this.packaging = string; - } - - /** {@inheritDoc} */ - @Override - public void setInceptionYear(String string) { - this.inceptionYear = string; - } - - /** {@inheritDoc} */ - @Override - public String getInceptionYear() { - return inceptionYear; - } - - /** {@inheritDoc} */ - @Override - public void setUrl(String string) { - this.url = string; - } - - /** {@inheritDoc} */ - @Override - public String getUrl() { - return url; - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getPrerequisites() - */ - @Override - public Prerequisites getPrerequisites() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setIssueManagement(org.apache.maven.model.IssueManagement) - */ - @Override - public void setIssueManagement(IssueManagement issueManagement) { - // nop - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getCiManagement() - */ - @Override - public CiManagement getCiManagement() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setCiManagement(org.apache.maven.model.CiManagement) - */ - @Override - public void setCiManagement(CiManagement ciManagement) { - // nop - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getIssueManagement() - */ - @Override - public IssueManagement getIssueManagement() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setDistributionManagement(org.apache.maven.model.DistributionManagement) - */ - @Override - public void setDistributionManagement(DistributionManagement distributionManagement) { - // nop - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getDistributionManagement() - */ - @Override - public DistributionManagement getDistributionManagement() { - return null; - } - - /** {@inheritDoc} */ - @Override - public void setDescription(String string) { - this.description = string; - } - - /** {@inheritDoc} */ - @Override - public String getDescription() { - return description; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setOrganization(org.apache.maven.model.Organization) - */ - @Override - public void setOrganization(Organization organization) { - // nop - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getOrganization() - */ - @Override - public Organization getOrganization() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setScm(org.apache.maven.model.Scm) - */ - @Override - public void setScm(Scm scm) { - // nop - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getScm() - */ - @Override - public Scm getScm() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setMailingLists(java.util.List) - */ - @Override - public void setMailingLists(List list) { - // nop - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getMailingLists() - */ - @Override - public List getMailingLists() { - return Collections.emptyList(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#addMailingList(org.apache.maven.model.MailingList) - */ - @Override - public void addMailingList(MailingList mailingList) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setDevelopers(java.util.List) - */ - @Override - public void setDevelopers(List list) { - // nop - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getDevelopers() - */ - @Override - public List getDevelopers() { - return Collections.emptyList(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#addDeveloper(org.apache.maven.model.Developer) - */ - @Override - public void addDeveloper(Developer developer) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setContributors(java.util.List) - */ - @Override - public void setContributors(List list) { - // nop - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getContributors() - */ - @Override - public List getContributors() { - return Collections.emptyList(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#addContributor(org.apache.maven.model.Contributor) - */ - @Override - public void addContributor(Contributor contributor) { - // nop - } - - /** {@inheritDoc} */ - @Override - public void setBuild(Build build) { - this.build = build; - } - - /** {@inheritDoc} */ - @Override - public Build getBuild() { - return build; - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getResources() - */ - @Override - public List getResources() { - return Collections.emptyList(); - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getTestResources() - */ - @Override - public List getTestResources() { - return Collections.emptyList(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#addResource(org.apache.maven.model.Resource) - */ - @Override - public void addResource(Resource resource) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#addTestResource(org.apache.maven.model.Resource) - */ - @Override - public void addTestResource(Resource resource) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setReporting(org.apache.maven.model.Reporting) - */ - @Override - public void setReporting(Reporting reporting) { - // nop - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getReporting() - */ - @Override - public Reporting getReporting() { - return null; - } - - /** {@inheritDoc} */ - @Override - public void setLicenses(List licenses) { - this.licenses = licenses; - } - - /** {@inheritDoc} */ - @Override - public List getLicenses() { - return licenses; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#addLicense(org.apache.maven.model.License) - */ - @Override - public void addLicense(License license) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setArtifacts(java.util.Set) - */ - @Override - public void setArtifacts(Set set) { - // nop - } - - /** - * By default, return Collections.EMPTY_SET. - * - * @see org.apache.maven.project.MavenProject#getArtifacts() - */ - @Override - public Set getArtifacts() { - return Collections.emptySet(); - } - - /** - * By default, return Collections.EMPTY_MAP. - * - * @see org.apache.maven.project.MavenProject#getArtifactMap() - */ - @Override - public Map getArtifactMap() { - return Collections.emptyMap(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setPluginArtifacts(java.util.Set) - */ - @Override - public void setPluginArtifacts(Set set) { - // nop - } - - /** - * By default, return Collections.EMPTY_SET. - * - * @see org.apache.maven.project.MavenProject#getPluginArtifacts() - */ - @Override - public Set getPluginArtifacts() { - return Collections.emptySet(); - } - - /** - * By default, return Collections.EMPTY_MAP. - * - * @see org.apache.maven.project.MavenProject#getPluginArtifactMap() - */ - @Override - public Map getPluginArtifactMap() { - return Collections.emptyMap(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setReportArtifacts(java.util.Set) - */ - @Override - public void setReportArtifacts(Set set) { - // nop - } - - /** - * By default, return Collections.EMPTY_SET. - * - * @see org.apache.maven.project.MavenProject#getReportArtifacts() - */ - @Override - public Set getReportArtifacts() { - return Collections.emptySet(); - } - - /** - * By default, return Collections.EMPTY_MAP. - * - * @see org.apache.maven.project.MavenProject#getReportArtifactMap() - */ - @Override - public Map getReportArtifactMap() { - return Collections.emptyMap(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setExtensionArtifacts(java.util.Set) - */ - @Override - public void setExtensionArtifacts(Set set) { - // nop - } - - /** - * By default, return Collections.EMPTY_SET. - * - * @see org.apache.maven.project.MavenProject#getExtensionArtifacts() - */ - @Override - public Set getExtensionArtifacts() { - return Collections.emptySet(); - } - - /** - * By default, return Collections.EMPTY_MAP. - * - * @see org.apache.maven.project.MavenProject#getExtensionArtifactMap() - */ - @Override - public Map getExtensionArtifactMap() { - return Collections.emptyMap(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setParentArtifact(org.apache.maven.artifact.Artifact) - */ - @Override - public void setParentArtifact(Artifact artifact) { - // nop - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getParentArtifact() - */ - @Override - public Artifact getParentArtifact() { - return null; - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getRepositories() - */ - @Override - public List getRepositories() { - return Collections.emptyList(); - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getReportPlugins() - */ - @Override - public List getReportPlugins() { - return Collections.emptyList(); - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getBuildPlugins() - */ - @Override - public List getBuildPlugins() { - return Collections.emptyList(); - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getModules() - */ - @Override - public List getModules() { - return Collections.emptyList(); - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getPluginManagement() - */ - @Override - public PluginManagement getPluginManagement() { - return null; - } - - /** - * By default, do nothing. - */ - public void addPlugin(Plugin plugin) { - // nop - } - - /** - * By default, do nothing. - * - * @param plugin - */ - public void injectPluginManagementInfo(Plugin plugin) { - // nop - } - - /** {@inheritDoc} */ - @Override - public List getCollectedProjects() { - return collectedProjects; - } - - /** {@inheritDoc} */ - @Override - public void setCollectedProjects(List list) { - this.collectedProjects = list; - } - - /** {@inheritDoc} */ - @Override - public void setPluginArtifactRepositories(List list) { - this.pluginArtifactRepositories = list; - } - - /** {@inheritDoc} */ - @Override - public List getPluginArtifactRepositories() { - return pluginArtifactRepositories; - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getDistributionManagementArtifactRepository() - */ - @Override - public ArtifactRepository getDistributionManagementArtifactRepository() { - return null; - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getPluginRepositories() - */ - @Override - public List getPluginRepositories() { - return Collections.emptyList(); - } - - /** {@inheritDoc} */ - @Override - public void setActiveProfiles(List list) { - activeProfiles = list; - } - - /** {@inheritDoc} */ - @Override - public List getActiveProfiles() { - return activeProfiles; - } - - /** {@inheritDoc} */ - @Override - public void addAttachedArtifact(Artifact artifact) { - if (attachedArtifacts == null) { - this.attachedArtifacts = new ArrayList<>(Collections.singletonList(artifact)); - } else { - attachedArtifacts.add(artifact); - } - } - - /** {@inheritDoc} */ - @Override - public List getAttachedArtifacts() { - return attachedArtifacts; - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getGoalConfiguration(java.lang.String, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Xpp3Dom getGoalConfiguration(String string, String string1, String string2, String string3) { - return null; - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getReportConfiguration(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Xpp3Dom getReportConfiguration(String string, String string1, String string2) { - return null; - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#getExecutionProject() - */ - @Override - public MavenProject getExecutionProject() { - return null; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#setExecutionProject(org.apache.maven.project.MavenProject) - */ - @Override - public void setExecutionProject(MavenProject mavenProject) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#writeModel(java.io.Writer) - */ - @Override - public void writeModel(Writer writer) throws IOException { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#writeOriginalModel(java.io.Writer) - */ - @Override - public void writeOriginalModel(Writer writer) throws IOException { - // nop - } - - /** {@inheritDoc} */ - @Override - public Set getDependencyArtifacts() { - return dependencyArtifacts; - } - - /** {@inheritDoc} */ - @Override - public void setDependencyArtifacts(Set set) { - this.dependencyArtifacts = set; - } - - /** {@inheritDoc} */ - @Override - public void setReleaseArtifactRepository(ArtifactRepository artifactRepository) { - this.releaseArtifactRepository = artifactRepository; - } - - /** {@inheritDoc} */ - @Override - public void setSnapshotArtifactRepository(ArtifactRepository artifactRepository) { - this.snapshotArtifactRepository = artifactRepository; - } - - /** {@inheritDoc} */ - @Override - public void setOriginalModel(Model model) { - this.originalModel = model; - } - - /** {@inheritDoc} */ - @Override - public Model getOriginalModel() { - return originalModel; - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getBuildExtensions() - */ - @Override - public List getBuildExtensions() { - return Collections.emptyList(); - } - - /** - * By default, return Collections.EMPTY_SET. - * - * @see org.apache.maven.project.MavenProject#createArtifacts(org.apache.maven.artifact.factory.ArtifactFactory, java.lang.String, org.apache.maven.artifact.resolver.filter.ArtifactFilter) - */ - @Override - public Set createArtifacts( - ArtifactFactory artifactFactory, String string, ArtifactFilter artifactFilter) { - return Collections.emptySet(); - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#addProjectReference(org.apache.maven.project.MavenProject) - */ - @Override - public void addProjectReference(MavenProject mavenProject) { - // nop - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.project.MavenProject#attachArtifact(java.lang.String, java.lang.String, java.io.File) - */ - @Override - public void attachArtifact(String string, String string1, File file) { - // nop - } - - /** - * By default, return a new instance of Properties. - * - * @see org.apache.maven.project.MavenProject#getProperties() - */ - @Override - public Properties getProperties() { - return new Properties(); - } - - /** - * By default, return Collections.EMPTY_LIST. - * - * @see org.apache.maven.project.MavenProject#getFilters() - */ - @Override - public List getFilters() { - return Collections.emptyList(); - } - - /** - * By default, return Collections.EMPTY_MAP. - * - * @see org.apache.maven.project.MavenProject#getProjectReferences() - */ - @Override - public Map getProjectReferences() { - return Collections.emptyMap(); - } - - /** {@inheritDoc} */ - @Override - public boolean isExecutionRoot() { - return executionRoot; - } - - /** {@inheritDoc} */ - @Override - public void setExecutionRoot(boolean b) { - this.executionRoot = b; - } - - /** {@inheritDoc} */ - @Override - public String getDefaultGoal() { - return defaultGoal; - } - - /** - * By default, return null. - * - * @see org.apache.maven.project.MavenProject#replaceWithActiveArtifact(org.apache.maven.artifact.Artifact) - */ - @Override - public Artifact replaceWithActiveArtifact(Artifact artifact) { - return null; - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactRepository.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactRepository.java deleted file mode 100644 index f680709..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactRepository.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * 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.plugin.testing.stubs; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.metadata.ArtifactMetadata; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; -import org.apache.maven.artifact.repository.Authentication; -import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; -import org.apache.maven.repository.Proxy; - -/** - * @author Brian Fox - */ -public class StubArtifactRepository implements ArtifactRepository { - private String baseDir = null; - - /** - * Default constructor - * - * @param dir the basedir - */ - public StubArtifactRepository(String dir) { - baseDir = dir; - } - - /** - * @return the artifactId. - * @see org.apache.maven.artifact.repository.ArtifactRepository#pathOf(org.apache.maven.artifact.Artifact) - */ - @Override - public String pathOf(Artifact artifact) { - return artifact.getId(); - } - - /** - * @return null. - * @see org.apache.maven.artifact.repository.ArtifactRepository#pathOfRemoteRepositoryMetadata(org.apache.maven.artifact.metadata.ArtifactMetadata) - */ - @Override - public String pathOfRemoteRepositoryMetadata(ArtifactMetadata artifactMetadata) { - return null; - } - - /** - * @return the filename of this metadata on the local repository. - * @see org.apache.maven.artifact.repository.ArtifactRepository#pathOfLocalRepositoryMetadata(org.apache.maven.artifact.metadata.ArtifactMetadata, org.apache.maven.artifact.repository.ArtifactRepository) - */ - @Override - public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) { - return metadata.getLocalFilename(repository); - } - - /** - * @return null. - * @see org.apache.maven.artifact.repository.ArtifactRepository#getUrl() - */ - @Override - public String getUrl() { - return null; - } - - /** - * @return basedir. - * @see org.apache.maven.artifact.repository.ArtifactRepository#getBasedir() - */ - @Override - public String getBasedir() { - return baseDir; - } - - /** - * @return null. - * @see org.apache.maven.artifact.repository.ArtifactRepository#getProtocol() - */ - @Override - public String getProtocol() { - return null; - } - - /** - * @return null. - * @see org.apache.maven.artifact.repository.ArtifactRepository#getId() - */ - @Override - public String getId() { - return null; - } - - /** - * @return null. - * @see org.apache.maven.artifact.repository.ArtifactRepository#getSnapshots() - */ - @Override - public ArtifactRepositoryPolicy getSnapshots() { - return null; - } - - /** - * @return null. - * @see org.apache.maven.artifact.repository.ArtifactRepository#getReleases() - */ - @Override - public ArtifactRepositoryPolicy getReleases() { - return null; - } - - /** - * @return null. - * @see org.apache.maven.artifact.repository.ArtifactRepository#getLayout() - */ - @Override - public ArtifactRepositoryLayout getLayout() { - return null; - } - - /** - * @return null. - * @see org.apache.maven.artifact.repository.ArtifactRepository#getKey() - */ - @Override - public String getKey() { - return null; - } - - /** - * @return false. - * @see org.apache.maven.artifact.repository.ArtifactRepository#isUniqueVersion() - */ - @Override - public boolean isUniqueVersion() { - return false; - } - - /** - * By default, do nothing. - * - * @see org.apache.maven.artifact.repository.ArtifactRepository#setBlacklisted(boolean) - */ - @Override - public void setBlacklisted(boolean blackListed) { - // nop - } - - /** - * @return false. - * @see org.apache.maven.artifact.repository.ArtifactRepository#isBlacklisted() - */ - @Override - public boolean isBlacklisted() { - return false; - } - - @Override - public Artifact find(Artifact artifact) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Authentication getAuthentication() { - return null; - } - - @Override - public Proxy getProxy() { - return null; - } - - @Override - public void setAuthentication(Authentication authentication) {} - - @Override - public void setId(String id) {} - - @Override - public void setLayout(ArtifactRepositoryLayout layout) {} - - @Override - public void setProxy(Proxy proxy) {} - - @Override - public void setReleaseUpdatePolicy(ArtifactRepositoryPolicy policy) {} - - @Override - public void setSnapshotUpdatePolicy(ArtifactRepositoryPolicy policy) {} - - @Override - public void setUrl(String url) {} - - @Override - public List findVersions(Artifact artifact) { - return Collections.emptyList(); - } - - @Override - public boolean isProjectAware() { - return false; - } - - @Override - public List getMirroredRepositories() { - return new ArrayList<>(0); - } - - @Override - public void setMirroredRepositories(List artifactRepositories) { - // no op - } - - @Override - public boolean isBlocked() { - return false; - } - - @Override - public void setBlocked(boolean blocked) { - // no op - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ArtifactStubFactoryTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/di/testing/SimpleDITest.java similarity index 52% rename from maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ArtifactStubFactoryTest.java rename to maven-plugin-testing-harness/src/test/java/org/apache/maven/api/di/testing/SimpleDITest.java index b7c9097..49fc6fa 100644 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ArtifactStubFactoryTest.java +++ b/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/di/testing/SimpleDITest.java @@ -16,28 +16,35 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugin.testing; +package org.apache.maven.api.di.testing; -import java.io.IOException; +import java.io.File; +import org.apache.maven.api.Session; +import org.apache.maven.api.di.Inject; +import org.apache.maven.api.di.Provides; +import org.apache.maven.api.plugin.testing.stubs.SessionMock; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.apache.maven.api.di.testing.MavenDIExtension.getBasedir; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@MavenDITest +public class SimpleDITest { + + private static final String LOCAL_REPO = getBasedir() + File.separator + "target" + File.separator + "local-repo"; + + @Inject + Session session; -public class ArtifactStubFactoryTest { @Test - public void testVersionChecks() throws IOException { - ArtifactStubFactory factory = new ArtifactStubFactory(); - assertTrue(factory.getReleaseArtifact().isRelease()); - assertFalse(factory.getReleaseArtifact().isSnapshot()); - assertTrue(factory.getSnapshotArtifact().isSnapshot()); - assertFalse(factory.getSnapshotArtifact().isRelease()); + void testSession() { + assertNotNull(session); + assertNotNull(session.getLocalRepository()); } - @Test - public void testCreateFiles() throws IOException { - ArtifactStubFactory factory = new ArtifactStubFactory(); - assertFalse(factory.isCreateFiles()); + @Provides + Session createSession() { + return SessionMock.getMockSession(LOCAL_REPO); } } diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/plugin/testing/ExpressionEvaluatorTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/plugin/testing/ExpressionEvaluatorTest.java index b287bbf..30834c5 100644 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/plugin/testing/ExpressionEvaluatorTest.java +++ b/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/plugin/testing/ExpressionEvaluatorTest.java @@ -18,15 +18,18 @@ */ package org.apache.maven.api.plugin.testing; -import javax.inject.Named; - +import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; -import com.google.inject.Provides; +import org.apache.maven.api.Project; import org.apache.maven.api.Session; +import org.apache.maven.api.di.Named; +import org.apache.maven.api.di.Provides; import org.apache.maven.api.plugin.MojoException; -import org.apache.maven.api.plugin.testing.stubs.SessionStub; +import org.apache.maven.api.plugin.annotations.Mojo; +import org.apache.maven.api.plugin.testing.stubs.ProjectStub; +import org.apache.maven.api.plugin.testing.stubs.SessionMock; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -42,16 +45,18 @@ public class ExpressionEvaluatorTest { private static final String LOCAL_REPO = "target/local-repo/"; - private static final String ARTIFACT_ID = "maven-test-mojo"; - private static final String COORDINATES = "groupId:" + ARTIFACT_ID + ":version:goal"; + private static final String GROUP_ID = "test"; + private static final String ARTIFACT_ID = "test-plugin"; + private static final String COORDINATES = GROUP_ID + ":" + ARTIFACT_ID + ":0.0.1-SNAPSHOT:goal"; private static final String CONFIG = "\n" + " \n" + " \n" + " \n" + + " " + GROUP_ID + "\n" + " " + ARTIFACT_ID + "\n" + " \n" - + " ${basedir}\n" - + " ${basedir}/workDirectory\n" + + " ${project.basedir}\n" + + " ${project.basedir}/workDirectory\n" + " \n" + " \n" + " \n" @@ -68,6 +73,7 @@ public void testInjection(ExpressionEvaluatorMojo mojo) { @Test @InjectMojo(goal = COORDINATES, pom = CONFIG) + @Basedir("${basedir}/target/test-classes") @MojoParameter(name = "param", value = "paramValue") public void testParam(ExpressionEvaluatorMojo mojo) { assertNotNull(mojo.basedir); @@ -88,11 +94,12 @@ public void testParams(ExpressionEvaluatorMojo mojo) { assertDoesNotThrow(mojo::execute); } - @Named(COORDINATES) + @Mojo(name = "goal") + @Named("test:test-plugin:0.0.1-SNAPSHOT:goal") // this one is usually generated by maven-plugin-plugin public static class ExpressionEvaluatorMojo implements org.apache.maven.api.plugin.Mojo { - private String basedir; + private Path basedir; - private String workdir; + private Path workdir; private String param; @@ -101,11 +108,11 @@ public static class ExpressionEvaluatorMojo implements org.apache.maven.api.plug /** {@inheritDoc} */ @Override public void execute() throws MojoException { - if (basedir == null || basedir.isEmpty()) { + if (basedir == null) { throw new MojoException("basedir was not injected."); } - if (workdir == null || workdir.isEmpty()) { + if (workdir == null) { throw new MojoException("workdir was not injected."); } else if (!workdir.startsWith(basedir)) { throw new MojoException("workdir does not start with basedir."); @@ -116,10 +123,17 @@ public void execute() throws MojoException { @Provides @SuppressWarnings("unused") Session session() { - Session session = SessionStub.getMockSession(LOCAL_REPO); + Session session = SessionMock.getMockSession(LOCAL_REPO); doReturn(new Properties()).when(session).getSystemProperties(); doReturn(new Properties()).when(session).getUserProperties(); doAnswer(iom -> Paths.get(MojoExtension.getBasedir())).when(session).getRootDirectory(); return session; } + + @Provides + Project project() { + ProjectStub project = new ProjectStub(); + project.setBasedir(Paths.get(MojoExtension.getBasedir())); + return project; + } } diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ExpressionEvaluatorMojo.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ExpressionEvaluatorMojo.java deleted file mode 100644 index 3586f9f..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ExpressionEvaluatorMojo.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.plugin.testing; - -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; - -/** - * @author Edwin Punzalan - */ -public class ExpressionEvaluatorMojo extends AbstractMojo { - private String basedir; - - private ArtifactRepository localRepository; - - private String workdir; - - /** {@inheritDoc} */ - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - if (basedir == null || basedir.isEmpty()) { - throw new MojoExecutionException("basedir was not injected."); - } - - if (localRepository == null) { - throw new MojoExecutionException("localRepository was not injected."); - } - - if (workdir == null || workdir.isEmpty()) { - throw new MojoExecutionException("workdir was not injected."); - } else if (!workdir.startsWith(basedir)) { - throw new MojoExecutionException("workdir does not start with basedir."); - } - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ExpressionEvaluatorTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ExpressionEvaluatorTest.java deleted file mode 100644 index 08849c5..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ExpressionEvaluatorTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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.plugin.testing; - -import java.io.StringReader; - -import org.apache.maven.plugin.MojoExecutionException; -import org.codehaus.plexus.configuration.PlexusConfiguration; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; - -/** - * @author Edwin Punzalan - */ -public class ExpressionEvaluatorTest extends AbstractMojoTestCase { - private Xpp3Dom pomDom; - - private PlexusConfiguration pluginConfiguration; - - /** {@inheritDoc} */ - @Override - protected void setUp() throws Exception { - super.setUp(); - - StringBuffer pom = new StringBuffer(); - - pom.append("").append("\n"); - pom.append(" ").append("\n"); - pom.append(" ").append("\n"); - pom.append(" ").append("\n"); - pom.append(" maven-test-mojo").append("\n"); - pom.append(" ").append("\n"); - pom.append(" ${basedir}").append("\n"); - pom.append(" ${basedir}/workDirectory").append("\n"); - pom.append(" ${localRepository}") - .append("\n"); - pom.append(" ").append("\n"); - pom.append(" ").append("\n"); - pom.append(" ").append("\n"); - pom.append(" ").append("\n"); - pom.append("").append("\n"); - - pomDom = Xpp3DomBuilder.build(new StringReader(pom.toString())); - - pluginConfiguration = extractPluginConfiguration("maven-test-mojo", pomDom); - } - - /** - * @throws Exception if any - */ - public void testInjection() throws Exception { - ExpressionEvaluatorMojo mojo = new ExpressionEvaluatorMojo(); - - mojo = (ExpressionEvaluatorMojo) configureMojo(mojo, pluginConfiguration); - - try { - mojo.execute(); - } catch (MojoExecutionException e) { - fail(e.getMessage()); - } - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoRuleTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoRuleTest.java deleted file mode 100644 index 105623d..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoRuleTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * 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.plugin.testing; - -import java.io.File; -import java.io.StringReader; -import java.util.Map; - -import org.codehaus.plexus.configuration.PlexusConfiguration; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Mirko Friedenhagen - */ -public class MojoRuleTest { - - private boolean beforeWasCalled = false; - - @Rule - public MojoRule rule = new MojoRule() { - - @Override - protected void before() throws Throwable { - beforeWasCalled = true; - } - }; - - private String pom; - - private Xpp3Dom pomDom; - - private PlexusConfiguration pluginConfiguration; - - /** {@inheritDoc} */ - @Before - public void setUp() throws Exception { - - pom = "" + "" - + "" - + "" - + "maven-simple-plugin" - + "" - + "valueOne" - + "valueTwo" - + "" - + "" - + "" - + "" - + ""; - - pomDom = Xpp3DomBuilder.build(new StringReader(pom)); - - pluginConfiguration = rule.extractPluginConfiguration("maven-simple-plugin", pomDom); - } - - /** - * @throws Exception if any - */ - @Test - public void testPluginConfigurationExtraction() throws Exception { - assertEquals("valueOne", pluginConfiguration.getChild("keyOne").getValue()); - - assertEquals("valueTwo", pluginConfiguration.getChild("keyTwo").getValue()); - } - - /** - * @throws Exception if any - */ - @Test - public void testMojoConfiguration() throws Exception { - SimpleMojo mojo = new SimpleMojo(); - - mojo = rule.configureMojo(mojo, pluginConfiguration); - - assertEquals("valueOne", mojo.getKeyOne()); - - assertEquals("valueTwo", mojo.getKeyTwo()); - } - - /** - * @throws Exception if any - */ - @Test - public void testVariableAccessWithoutGetter() throws Exception { - SimpleMojo mojo = new SimpleMojo(); - - mojo = rule.configureMojo(mojo, pluginConfiguration); - - assertEquals("valueOne", rule.getVariableValueFromObject(mojo, "keyOne")); - - assertEquals("valueTwo", rule.getVariableValueFromObject(mojo, "keyTwo")); - } - - /** - * @throws Exception if any - */ - @Test - public void testVariableAccessWithoutGetter2() throws Exception { - SimpleMojo mojo = new SimpleMojo(); - - mojo = rule.configureMojo(mojo, pluginConfiguration); - - Map map = rule.getVariablesAndValuesFromObject(mojo); - - assertEquals("valueOne", map.get("keyOne")); - - assertEquals("valueTwo", map.get("keyTwo")); - } - - /** - * @throws Exception if any - */ - @Test - public void testSettingMojoVariables() throws Exception { - SimpleMojo mojo = new SimpleMojo(); - - mojo = rule.configureMojo(mojo, pluginConfiguration); - - rule.setVariableValueToObject(mojo, "keyOne", "myValueOne"); - - assertEquals("myValueOne", rule.getVariableValueFromObject(mojo, "keyOne")); - } - - @Test - @WithoutMojo - public void testNoRuleWrapper() throws Exception { - assertFalse("before executed although WithMojo annotation was added", beforeWasCalled); - } - - @Test - public void testWithRuleWrapper() throws Exception { - assertTrue("before executed because WithMojo annotation was not added", beforeWasCalled); - } - - /** - * @throws Exception if any - */ - @Test - public void testLookupInitializedMojo() throws Exception { - File pomBaseDir = new File("src/test/projects/property"); - ParametersMojo mojo = rule.lookupConfiguredMojo(pomBaseDir, "parameters"); - assertEquals("default", rule.getVariableValueFromObject(mojo, "withDefault")); - assertEquals("propertyValue", rule.getVariableValueFromObject(mojo, "withProperty")); - assertEquals("propertyValue", rule.getVariableValueFromObject(mojo, "withPropertyAndDefault")); - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoTestCaseTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoTestCaseTest.java deleted file mode 100644 index 1fa8947..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoTestCaseTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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.plugin.testing; - -import java.io.StringReader; -import java.util.Map; - -import org.apache.maven.api.plugin.testing.MojoTest; -import org.codehaus.plexus.configuration.PlexusConfiguration; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; - -/** - * @author Jason van Zyl - */ -@MojoTest -public class MojoTestCaseTest extends AbstractMojoTestCase { - private String pom; - - private Xpp3Dom pomDom; - - private PlexusConfiguration pluginConfiguration; - - /** {@inheritDoc} */ - @Override - protected void setUp() throws Exception { - super.setUp(); - - pom = "" + "" - + "" - + "" - + "maven-simple-plugin" - + "" - + "valueOne" - + "valueTwo" - + "" - + "" - + "" - + "" - + ""; - - pomDom = Xpp3DomBuilder.build(new StringReader(pom)); - - pluginConfiguration = extractPluginConfiguration("maven-simple-plugin", pomDom); - } - - /** - * @throws Exception if any - */ - public void testPluginConfigurationExtraction() throws Exception { - assertEquals("valueOne", pluginConfiguration.getChild("keyOne").getValue()); - - assertEquals("valueTwo", pluginConfiguration.getChild("keyTwo").getValue()); - } - - /** - * @throws Exception if any - */ - public void testMojoConfiguration() throws Exception { - SimpleMojo mojo = new SimpleMojo(); - - mojo = (SimpleMojo) configureMojo(mojo, pluginConfiguration); - - assertEquals("valueOne", mojo.getKeyOne()); - - assertEquals("valueTwo", mojo.getKeyTwo()); - } - - /** - * @throws Exception if any - */ - public void testVariableAccessWithoutGetter() throws Exception { - SimpleMojo mojo = new SimpleMojo(); - - mojo = (SimpleMojo) configureMojo(mojo, pluginConfiguration); - - assertEquals("valueOne", (String) getVariableValueFromObject(mojo, "keyOne")); - - assertEquals("valueTwo", (String) getVariableValueFromObject(mojo, "keyTwo")); - } - - /** - * @throws Exception if any - */ - public void testVariableAccessWithoutGetter2() throws Exception { - SimpleMojo mojo = new SimpleMojo(); - - mojo = (SimpleMojo) configureMojo(mojo, pluginConfiguration); - - Map map = getVariablesAndValuesFromObject(mojo); - - assertEquals("valueOne", (String) map.get("keyOne")); - - assertEquals("valueTwo", (String) map.get("keyTwo")); - } - - /** - * @throws Exception if any - */ - public void testSettingMojoVariables() throws Exception { - SimpleMojo mojo = new SimpleMojo(); - - mojo = (SimpleMojo) configureMojo(mojo, pluginConfiguration); - - setVariableValueToObject(mojo, "keyOne", "myValueOne"); - - assertEquals("myValueOne", (String) getVariableValueFromObject(mojo, "keyOne")); - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ParametersMojo.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ParametersMojo.java deleted file mode 100644 index 77e52d9..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ParametersMojo.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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.plugin.testing; - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; - -public class ParametersMojo extends AbstractMojo { - public String plain; - - public String withProperty; - - public String withDefault; - - public String withPropertyAndDefault; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - getLog().info("Plain value = " + plain); - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ParametersMojoTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ParametersMojoTest.java deleted file mode 100644 index ce7869c..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/ParametersMojoTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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.plugin.testing; - -import java.io.File; - -import org.apache.maven.execution.DefaultMavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuilder; -import org.apache.maven.project.ProjectBuildingException; -import org.apache.maven.project.ProjectBuildingRequest; -import org.eclipse.aether.DefaultRepositorySystemSession; - -public class ParametersMojoTest extends AbstractMojoTestCase { - public void testDefault() throws Exception { - MavenProject project = readMavenProject(new File("src/test/projects/default")); - - ParametersMojo mojo = (ParametersMojo) lookupConfiguredMojo(project, "parameters"); - - assertNull(mojo.plain); - assertNull(mojo.withProperty); - assertEquals("default", mojo.withDefault); - assertEquals("default", mojo.withPropertyAndDefault); - } - - public void testExplicit() throws Exception { - MavenProject project = readMavenProject(new File("src/test/projects/explicit")); - - ParametersMojo mojo = (ParametersMojo) lookupConfiguredMojo(project, "parameters"); - - assertEquals("explicitValue", mojo.plain); - assertEquals("explicitWithPropertyValue", mojo.withProperty); - assertEquals("explicitWithDefaultValue", mojo.withDefault); - assertEquals("explicitWithPropertyAndDefaultValue", mojo.withPropertyAndDefault); - } - - public void testDefaultWithProperty() throws Exception { - MavenProject project = readMavenProject(new File("src/test/projects/default")); - MavenSession session = newMavenSession(project); - MojoExecution execution = newMojoExecution("parameters"); - - session.getUserProperties().put("property", "propertyValue"); - ParametersMojo mojo = (ParametersMojo) lookupConfiguredMojo(session, execution); - - assertNull(mojo.plain); - assertEquals("propertyValue", mojo.withProperty); - assertEquals("default", mojo.withDefault); - assertEquals("propertyValue", mojo.withPropertyAndDefault); - } - - public void testExplicitWithProperty() throws Exception { - MavenProject project = readMavenProject(new File("src/test/projects/explicit")); - MavenSession session = newMavenSession(project); - MojoExecution execution = newMojoExecution("parameters"); - - session.getUserProperties().put("property", "propertyValue"); - ParametersMojo mojo = (ParametersMojo) lookupConfiguredMojo(session, execution); - - assertEquals("explicitValue", mojo.plain); - assertEquals("explicitWithPropertyValue", mojo.withProperty); - assertEquals("explicitWithDefaultValue", mojo.withDefault); - assertEquals("explicitWithPropertyAndDefaultValue", mojo.withPropertyAndDefault); - } - - protected MavenProject readMavenProject(File basedir) throws ProjectBuildingException, Exception { - File pom = new File(basedir, "pom.xml"); - MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - request.setBaseDirectory(basedir); - ProjectBuildingRequest configuration = request.getProjectBuildingRequest(); - configuration.setRepositorySession(new DefaultRepositorySystemSession()); - MavenProject project = - lookup(ProjectBuilder.class).build(pom, configuration).getProject(); - assertNotNull(project); - return project; - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/PluginArtifactFileTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/PluginArtifactFileTest.java deleted file mode 100644 index 6025f21..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/PluginArtifactFileTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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.plugin.testing; - -import java.util.List; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.MojoExecution; - -public class PluginArtifactFileTest extends AbstractMojoTestCase { - private static final String FS = System.getProperty("file.separator"); - - public void testArtifact() throws Exception { - MojoExecution execution = newMojoExecution("parameters"); // TODO dedicated test mojo - - List artifacts = - execution.getMojoDescriptor().getPluginDescriptor().getArtifacts(); - - assertEquals(1, artifacts.size()); - - Artifact artifact = artifacts.get(0); - assertEquals("test", artifact.getGroupId()); - assertEquals("test-plugin", artifact.getArtifactId()); - assertEquals("0.0.1-SNAPSHOT", artifact.getBaseVersion()); - assertTrue(artifact.getFile().getAbsolutePath().endsWith(FS + "target" + FS + "test-classes")); - } - - // TODO find a way to automate testing of jar:file:/ test plugin URLs -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/SimpleMojo.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/SimpleMojo.java deleted file mode 100644 index e284ea2..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/SimpleMojo.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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.plugin.testing; - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; - -/** - * @author Jason van Zyl - */ -public class SimpleMojo extends AbstractMojo { - private String keyOne; - - private String keyTwo; - - public String getKeyOne() { - return keyOne; - } - - public String getKeyTwo() { - return keyTwo; - } - - @Override - public void execute() throws MojoExecutionException {} -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/TestSilentLog.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/TestSilentLog.java deleted file mode 100644 index 69b2ed3..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/TestSilentLog.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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.plugin.testing; - -import junit.framework.TestCase; -import org.apache.maven.plugin.logging.Log; -import org.codehaus.plexus.logging.Logger; - -public class TestSilentLog extends TestCase { - - public void testLog() { - Log log = new SilentLog(); - String text = new String("Text"); - Throwable e = new RuntimeException(); - log.debug(text); - log.debug(text, e); - log.debug(e); - log.info(text); - log.info(text, e); - log.info(e); - log.warn(text); - log.warn(text, e); - log.warn(e); - log.error(text); - log.error(text, e); - log.error(e); - log.isDebugEnabled(); - log.isErrorEnabled(); - log.isWarnEnabled(); - log.isInfoEnabled(); - } - - public void testLogger() { - Logger log = new SilentLog(); - String text = new String("Text"); - Throwable e = new RuntimeException(); - - log.debug(text); - log.debug(text, e); - log.error(text); - log.error(text, e); - log.warn(text); - log.warn(text, e); - log.info(text); - log.info(text, e); - - log.fatalError(text); - log.fatalError(text, e); - log.getChildLogger(text); - log.getName(); - log.getThreshold(); - log.isDebugEnabled(); - log.isErrorEnabled(); - log.isFatalErrorEnabled(); - log.isInfoEnabled(); - log.isWarnEnabled(); - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/junit5/Junit5Test.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/junit5/Junit5Test.java deleted file mode 100644 index 9da0036..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/junit5/Junit5Test.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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.plugin.testing.junit5; - -import javax.inject.Inject; - -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugin.testing.ParametersMojo; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; - -@MojoTest -class Junit5Test { - - private static final String POM = "" - + "" - + " " - + " " - + " test-plugin" - + " " - + " " - + " " - + " " - + "" + ""; - - @Inject - private Log log; - - @Test - @InjectMojo(goal = "test:test-plugin:0.0.1-SNAPSHOT:parameters", pom = POM) - void simpleMojo(ParametersMojo mojo) { - assertEquals(log, mojo.getLog()); - assertDoesNotThrow(mojo::execute); - } - - @Test - @InjectMojo(goal = "test:test-plugin:0.0.1-SNAPSHOT:parameters", pom = POM) - @MojoParameter(name = "plain", value = "plainValue") - @MojoParameter(name = "withDefault", value = "withDefaultValue") - void simpleMojoWithParameters(ParametersMojo mojo) { - assertEquals("plainValue", mojo.plain); - assertEquals("withDefaultValue", mojo.withDefault); - assertDoesNotThrow(mojo::execute); - } - - @Test - @InjectMojo(goal = "test:test-plugin:0.0.1-SNAPSHOT:parameters", pom = POM) - @MojoParameter(name = "plain", value = "plainValue") - void simpleMojoWithParameter(ParametersMojo mojo) { - assertEquals("plainValue", mojo.plain); - assertDoesNotThrow(mojo::execute); - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/resources/TestResourcesTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/resources/TestResourcesTest.java deleted file mode 100644 index 8ce1ecb..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/resources/TestResourcesTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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.plugin.testing.resources; - -import org.junit.Test; - -public class TestResourcesTest { - public TestResources resources = new TestResources(); - - @Test(expected = IllegalStateException.class) - public void testNoRuleAnnotation() throws Exception { - resources.getBasedir("dummy"); - } -} diff --git a/maven-plugin-testing-harness/src/test/projects/default/pom.xml b/maven-plugin-testing-harness/src/test/projects/default/pom.xml deleted file mode 100644 index e0dc4b3..0000000 --- a/maven-plugin-testing-harness/src/test/projects/default/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - 4.0.0 - - test - test-test - 1.0-SNAPSHOT - jar - - - - - test - test-plugin - 0.0.1-SNAPSHOT - - - test - - test - - compile - - - - - - diff --git a/maven-plugin-testing-harness/src/test/projects/explicit/pom.xml b/maven-plugin-testing-harness/src/test/projects/explicit/pom.xml deleted file mode 100644 index 06628e9..0000000 --- a/maven-plugin-testing-harness/src/test/projects/explicit/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - 4.0.0 - - test - test-test - 1.0-SNAPSHOT - jar - - - - - test - test-plugin - 0.0.1-SNAPSHOT - - - test - - test - - compile - - - - explicitValue - explicitWithPropertyValue - explicitWithDefaultValue - explicitWithPropertyAndDefaultValue - - - - - diff --git a/maven-plugin-testing-harness/src/test/projects/property/pom.xml b/maven-plugin-testing-harness/src/test/projects/property/pom.xml deleted file mode 100644 index 167b598..0000000 --- a/maven-plugin-testing-harness/src/test/projects/property/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - 4.0.0 - - test - test-test - 1.0-SNAPSHOT - jar - - - propertyValue - - - - - - test - test-plugin - 0.0.1-SNAPSHOT - - - test - - test - - compile - - - - - - diff --git a/maven-plugin-testing-harness/src/test/resources/META-INF/maven/org.apache.maven.api.di.Inject b/maven-plugin-testing-harness/src/test/resources/META-INF/maven/org.apache.maven.api.di.Inject new file mode 100644 index 0000000..2a771d7 --- /dev/null +++ b/maven-plugin-testing-harness/src/test/resources/META-INF/maven/org.apache.maven.api.di.Inject @@ -0,0 +1,19 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +org.apache.maven.api.plugin.testing.ExpressionEvaluatorTest$ExpressionEvaluatorMojo \ No newline at end of file diff --git a/maven-plugin-testing-harness/src/test/resources/META-INF/maven/plugin.xml b/maven-plugin-testing-harness/src/test/resources/META-INF/maven/plugin.xml index d442272..6657446 100644 --- a/maven-plugin-testing-harness/src/test/resources/META-INF/maven/plugin.xml +++ b/maven-plugin-testing-harness/src/test/resources/META-INF/maven/plugin.xml @@ -20,7 +20,7 @@ specific language governing permissions and limitations under the License. --> - + test-plugin test @@ -31,19 +31,31 @@ under the License. true - parameters - false - true - false + goal + true false - false + false true org.apache.maven.plugin.testing.ParametersMojo java - per-lookup - once-per-session - false + + basedir + java.nio.file.Path + + + workdir + java.nio.file.Path + + + param + java.lang.String + + + param2 + java.lang.String + + - - - ${property} - ${property} - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index 4cea8e8..6d530ae 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ under the License. org.apache.maven maven-parent - 40 + 42 @@ -65,9 +65,9 @@ under the License. 3.2.1 - 4.0.0-alpha-8 + 4.0.0-beta-3 plugin-testing-archives/LATEST - 8 + 17 2023-11-07T21:58:12Z