Java Code Examples for org.apache.maven.execution.MavenSession

The following examples show how to use org.apache.maven.execution.MavenSession. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: heroku-maven-plugin   Source File: MojoExecutor.java    License: MIT License 6 votes vote down vote up
public static Path createDependencyListFile(MavenProject mavenProject,
                                            MavenSession mavenSession,
                                            BuildPluginManager pluginManager) throws MojoExecutionException, IOException {

    Path path = Files.createTempFile("heroku-maven-plugin", "mvn-dependency-list.log");

    executeMojo(
            plugin(
                    groupId("org.apache.maven.plugins"),
                    artifactId("maven-dependency-plugin"),
                    version("2.4")
            ),
            goal("list"),
            configuration(
                    element(name("outputFile"), path.toString())
            ),
            executionEnvironment(
                    mavenProject,
                    mavenSession,
                    pluginManager
            )
    );

    return path;
}
 
Example 2
@Override
public void afterProjectsRead(MavenSession session) {
    if (ENABLED) {
        // Init state
        supportedProjectDir = null;
        projectConfig = null;
        debug("collector enabled");
        try {
            // Ensure that we support this project
            supportedProjectDir = assertSupportedProject(session);

            // Install our listener so we can know if compilation occurred and succeeded
            final MavenExecutionRequest request = session.getRequest();
            request.setExecutionListener(new EventListener(request.getExecutionListener()));
        } catch (IllegalStateException e) {
            supportedProjectDir = null;
        }
    } else {
        debug("collector disabled");
    }
}
 
Example 3
Source Project: docker-maven-plugin   Source File: BuildMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
private BuildMojo setupMojo(final File pom) throws Exception {
  final MavenProject project = new ProjectStub(pom);
  final MavenSession session = newMavenSession(project);
  // for some reason the superclass method newMavenSession() does not copy properties from the
  // project model to the session. This is needed for the use of ExpressionEvaluator in BuildMojo.
  session.getRequest().setUserProperties(project.getModel().getProperties());

  final MojoExecution execution = newMojoExecution("build");
  final BuildMojo mojo = (BuildMojo) this.lookupConfiguredMojo(session, execution);
  mojo.buildDirectory = "target";
  // Because test poms are loaded from test/resources, tagInfoFile will default to
  // test/resources/target/image_info.json. Writing the json file to that location will fail
  // because target doesn't exist. So force it to use project's target directory.
  // But don't overwrite it if a test sets a non-default value.
  if (mojo.tagInfoFile.contains("src/test/resources")) {
    mojo.tagInfoFile = "target/image_info.json";
  }
  mojo.session = session;
  mojo.execution = execution;
  return mojo;
}
 
Example 4
@Test
public void testReference_testCompile() throws Exception {
  File basedir = resources.getBasedir("compile-jdt-classpath-visibility/reference");

  MavenProject project = mojos.readMavenProject(basedir);
  addDependency(project, "dependency", DEPENDENCY);

  MavenSession session = mojos.newMavenSession(project);

  Xpp3Dom[] params = new Xpp3Dom[] {param("compilerId", "jdt"), //
      param("transitiveDependencyReference", "error"), //
      param("privatePackageReference", "error")};

  mojos.executeMojo(session, project, "compile", params);

  mojos.executeMojo(session, project, "testCompile", params);
}
 
Example 5
Source Project: docker-maven-plugin   Source File: MappingTrackArchiver.java    License: Apache License 2.0 6 votes vote down vote up
private File getLocalMavenRepoFile(MavenSession session, File source) {
    ArtifactRepository localRepo = session.getLocalRepository();
    if (localRepo == null) {
        log.warn("No local repo found so not adding any extra watches in the local repository");
        return null;
    }

    Artifact artifact = getArtifactFromJar(source);
    if (artifact != null) {
        try {
            return new File(localRepo.getBasedir(), localRepo.pathOf(artifact));
        } catch (InvalidArtifactRTException e) {
            log.warn("Cannot get the local repository path for %s in base dir %s : %s",
                     artifact, localRepo.getBasedir(), e.getMessage());
        }
    }
    return null;
}
 
Example 6
@Test
public void testClasspathScope() throws Exception {
  File basedir = resources.getBasedir();
  MavenProject project = mojos.readMavenProject(basedir);
  MavenSession session = mojos.newMavenSession(project);

  File providedScoped = temp.newFile("provided.jar").getCanonicalFile();
  File testScoped = temp.newFile("test.jar").getCanonicalFile();

  mojos.newDependency(providedScoped).setGroupId("g").setArtifactId("provided").setScope("provided").addTo(project);
  mojos.newDependency(testScoped).setGroupId("g").setArtifactId("test").setScope("test").addTo(project);

  mojos.executeMojo(session, project, "testProperties");

  Map<String, String> properties = readProperties(basedir);
  Assert.assertEquals(new File(basedir, "target/classes").getCanonicalPath(), properties.get("classpath"));
}
 
Example 7
Source Project: dew   Source File: MojoExecutor.java    License: Apache License 2.0 6 votes vote down vote up
public void execute( MavenSession session, List<MojoExecution> mojoExecutions, ProjectIndex projectIndex )
    throws LifecycleExecutionException

{
    if (SkipCheck.skip(session.getCurrentProject().getBasedir())
            && mojoExecutions.stream().map(MojoExecution::getGoal).map(String::toLowerCase)
            .anyMatch(s ->
                    s.contains("group.idealworld.dew:dew-maven-plugin:release")
                            || s.contains("dew:release")
                            || s.contains("deploy"))) {
        return;
    }
    DependencyContext dependencyContext = newDependencyContext( session, mojoExecutions );

    PhaseRecorder phaseRecorder = new PhaseRecorder( session.getCurrentProject() );

    for ( MojoExecution mojoExecution : mojoExecutions )
    {
        execute( session, mojoExecution, projectIndex, dependencyContext, phaseRecorder );
    }
}
 
Example 8
Source Project: pom-manipulation-ext   Source File: PropertiesUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "deprecation" )
private ManipulationSession createUpdateSession() throws Exception
{
    ManipulationSession session = new ManipulationSession();

    session.setState( new DependencyState( p ) );
    session.setState( new VersioningState( p ) );
    session.setState( new CommonState( p ) );

    final MavenExecutionRequest req =
                    new DefaultMavenExecutionRequest().setUserProperties( p ).setRemoteRepositories( Collections.emptyList() );

    final PlexusContainer container = new DefaultPlexusContainer();
    final MavenSession mavenSession = new MavenSession( container, null, req, new DefaultMavenExecutionResult() );

    session.setMavenSession( mavenSession );

    return session;
}
 
Example 9
Source Project: pom-manipulation-ext   Source File: CliTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void checkLocalRepositoryWithDefaults() throws Exception
{
    Cli c = new Cli();
    File settings = writeSettings( temp.newFile());

    TestUtils.executeMethod( c, "run", new Object[] { new String[] { "-s", settings.toString()} } );

    ManipulationSession session = (ManipulationSession) FieldUtils.readField( c, "session", true );
    MavenSession ms = (MavenSession)FieldUtils.readField( session, "mavenSession", true );

    assertEquals( ms.getRequest().getLocalRepository().getBasedir(),
                  ms.getRequest().getLocalRepositoryPath().toString() );
    assertEquals( "File " + new File( ms.getRequest().getLocalRepository().getBasedir() ).getParentFile().toString()
                                  + " was not equal to " + System.getProperty( "user.home" ) + File.separatorChar
                                  + ".m2",
                  new File( ms.getRequest().getLocalRepository().getBasedir() ).getParentFile().toString(),
                  System.getProperty( "user.home" ) + File.separatorChar + ".m2" );

}
 
Example 10
Source Project: spring-cloud-contract   Source File: ChangeDetector.java    License: Apache License 2.0 6 votes vote down vote up
static boolean inputFilesChangeDetected(File contractsDirectory,
		MojoExecution mojoExecution, MavenSession session)
		throws MojoExecutionException {

	IncrementalBuildHelper incrementalBuildHelper = new IncrementalBuildHelper(
			mojoExecution, session);

	DirectoryScanner scanner = incrementalBuildHelper.getDirectoryScanner();
	scanner.setBasedir(contractsDirectory);
	scanner.scan();
	boolean changeDetected = incrementalBuildHelper.inputFileTreeChanged(scanner);
	if (scanner.getIncludedFiles().length == 0) {
		// at least one input file must exist to consider changed/unchanged
		// return true to skip incremental build and make visible no input file at all
		return true;
	}
	return changeDetected;
}
 
Example 11
Source Project: takari-smart-builder   Source File: SmartBuilderImpl.java    License: Apache License 2.0 6 votes vote down vote up
SmartBuilderImpl(LifecycleModuleBuilder lifecycleModuleBuilder, MavenSession session,
    ReactorContext reactorContext, TaskSegment taskSegment, Set<MavenProject> projects) {
  this.lifecycleModuleBuilder = lifecycleModuleBuilder;
  this.rootSession = session;
  this.reactorContext = reactorContext;
  this.taskSegment = taskSegment;

  this.degreeOfConcurrency = Integer.valueOf(session.getRequest().getDegreeOfConcurrency());

  final Comparator<MavenProject> projectComparator = ProjectComparator.create(session);

  this.reactorBuildQueue = new ReactorBuildQueue(projects, session.getProjectDependencyGraph());
  this.executor = new ProjectExecutorService(degreeOfConcurrency, projectComparator);

  this.stats = ReactorBuildStats.create(projects);
}
 
Example 12
Source Project: dew   Source File: MojoExecutor.java    License: Apache License 2.0 6 votes vote down vote up
public void execute( MavenSession session, List<MojoExecution> mojoExecutions, ProjectIndex projectIndex )
    throws LifecycleExecutionException

{
    if (SkipCheck.skip(session.getCurrentProject().getBasedir())
            && mojoExecutions.stream().map(MojoExecution::getGoal).map(String::toLowerCase)
            .anyMatch(s ->
                    s.contains("group.idealworld.dew:dew-maven-plugin:release")
                            || s.contains("dew:release")
                            || s.contains("deploy"))) {
        return;
    }
    DependencyContext dependencyContext = newDependencyContext( session, mojoExecutions );

    PhaseRecorder phaseRecorder = new PhaseRecorder( session.getCurrentProject() );

    for ( MojoExecution mojoExecution : mojoExecutions )
    {
        execute( session, mojoExecution, projectIndex, dependencyContext, phaseRecorder );
    }
}
 
Example 13
Source Project: takari-lifecycle   Source File: CompileTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testImplicitClassfileGeneration() throws Exception {
  // javac automatically generates class files from sources found on classpath in some cases
  // the point of this test is to make sure this behaviour is disabled

  File dependency = compile("compile/basic");
  cp(dependency, "src/main/java/basic/Basic.java", "target/classes/basic/Basic.java");
  touch(dependency, "target/classes/basic/Basic.java"); // must be newer than .class file

  File basedir = resources.getBasedir("compile/implicit-classfile");
  MavenProject project = mojos.readMavenProject(basedir);
  MavenSession session = mojos.newMavenSession(project);
  MojoExecution execution = mojos.newMojoExecution();

  addDependency(project, "dependency", new File(dependency, "target/classes"));

  mojos.executeMojo(session, project, execution);

  mojos.assertBuildOutputs(new File(basedir, "target/classes"), "implicit/Implicit.class");
}
 
Example 14
Source Project: heroku-maven-plugin   Source File: MojoExecutor.java    License: MIT License 6 votes vote down vote up
public static void copyDependenciesToBuildDirectory(MavenProject mavenProject,
                                                    MavenSession mavenSession,
                                                    BuildPluginManager pluginManager) throws MojoExecutionException {
    executeMojo(
            plugin(
                    groupId("org.apache.maven.plugins"),
                    artifactId("maven-dependency-plugin"),
                    version("2.4")
            ),
            goal("copy-dependencies"),
            configuration(
                    element(name("outputDirectory"), "${project.build.directory}/dependency")
            ),
            executionEnvironment(
                    mavenProject,
                    mavenSession,
                    pluginManager
            )
    );
}
 
Example 15
Source Project: wisdom   Source File: WatchersTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWatchers() {
    Properties properties = new Properties();
    MavenSession session = mock(MavenSession.class);
    when(session.getExecutionProperties()).thenReturn(properties);

    // Nothing added.
    assertThat(Watchers.all(session)).isEmpty();

    // Added watchers.
    Watcher watcher1 = mock(Watcher.class);
    Watchers.add(session, watcher1);
    assertThat(Watchers.all(session)).hasSize(1);

    Watcher watcher2 = mock(Watcher.class);
    Watchers.add(session, watcher2);
    assertThat(Watchers.all(session)).hasSize(2);

    // Remove watchers
    assertThat(Watchers.remove(session, watcher1)).isTrue();
    assertThat(Watchers.remove(session, null)).isFalse();
    assertThat(Watchers.all(session)).hasSize(1);
}
 
Example 16
Source Project: smart-testing   Source File: SmartTestingMavenConfigurer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    Log.setLoggerFactory(new MavenExtensionLoggerFactory(mavenLogger));

    loadConfigAndCheckIfInstallationShouldBeSkipped(session);
    if (skipExtensionInstallation) {
        return;
    }

    logger.debug("Version: %s", ExtensionVersion.version().toString());
    logger.debug("Applied user properties: %s", session.getUserProperties());

    File projectDirectory = session.getTopLevelProject().getModel().getProjectDirectory();
    logger.info("Enabling extension.");
    configureExtension(session, configuration);
    calculateChanges(projectDirectory, configuration);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> purgeLocalStorageAndExportPom(session)));
}
 
Example 17
Source Project: smart-testing   Source File: SmartTestingMavenConfigurer.java    License: Apache License 2.0 6 votes vote down vote up
private void loadConfigAndCheckIfInstallationShouldBeSkipped(MavenSession session) {
    SkipInstallationChecker skipInstallationChecker = new SkipInstallationChecker(session);
    skipExtensionInstallation = skipInstallationChecker.shouldSkip();
    if (skipExtensionInstallation) {
        logExtensionDisableReason(Log.getLogger(), skipInstallationChecker.getReason());
        return;
    }

    File executionRootDirectory = new File(session.getExecutionRootDirectory());
    configuration = ConfigurationLoader.load(executionRootDirectory, this::isProjectRootDirectory);
    Log.setLoggerFactory(new MavenExtensionLoggerFactory(mavenLogger, configuration));
    logger = Log.getLogger();
    if (skipInstallationChecker.shouldSkipForConfiguration(configuration)) {
        skipExtensionInstallation = true;
        logExtensionDisableReason(logger, skipInstallationChecker.getReason());
    }
}
 
Example 18
Source Project: jkube   Source File: MojoParameters.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public MojoParameters(MavenSession session, MavenProject project, MavenArchiveConfiguration archive, MavenFileFilter mavenFileFilter,
                      MavenReaderFilter mavenFilterReader, Settings settings, String sourceDirectory, String outputDirectory, List<MavenProject> reactorProjects) {
    this.archive = archive;
    this.session = session;
    this.mavenFileFilter = mavenFileFilter;
    this.mavenFilterReader = mavenFilterReader;
    this.project = project;
    this.settings = settings;

    this.sourceDirectory = sourceDirectory;
    this.outputDirectory = outputDirectory;

    this.reactorProjects = reactorProjects;
}
 
Example 19
private Mojo configureMojo(final String parameter, final String value) throws Exception {
	final MavenSession mavenSession = mojoRule.newMavenSession(getMavenProject(DEFAULT_CONFIG));
	final MojoExecution mojoExecution = mojoRule.newMojoExecution(GOAL_NAME);
	final Xpp3Dom configuration = new Xpp3Dom("configuration");
	final Xpp3Dom generationConfig = new Xpp3Dom("generationConfig");
	final Xpp3Dom useBigDecimal = new Xpp3Dom(parameter);
	useBigDecimal.setValue(value);
	generationConfig.addChild(useBigDecimal);

	configuration.addChild(generationConfig);
	mojoExecution.setConfiguration(configuration);

	return mojoRule.lookupConfiguredMojo(mavenSession, mojoExecution);
}
 
Example 20
private void compile(File basedir, File processor, String executionId) throws Exception {
  MavenProject project = mojos.readMavenProject(basedir);
  MavenSession session = mojos.newMavenSession(project);
  MojoExecution execution = mojos.newMojoExecution();
  MojoExecution cloned = new MojoExecution(execution.getMojoDescriptor(), executionId, null);
  cloned.setConfiguration(execution.getConfiguration());
  execution.getConfiguration().addChild(newParameter("proc", Proc.none.name()));
  addDependency(project, "processor", new File(processor, "target/classes"));
  mojos.executeMojo(session, project, cloned);
}
 
Example 21
Source Project: helidon-build-tools   Source File: MavenPluginHelper.java    License: Apache License 2.0 5 votes vote down vote up
public <T> T getMojo (String pom, File dir, String execName, Class<T> clazz) throws Exception {
    MavenProject project = newMavenProject(pom, dir);
    MavenSession session = newMavenSession(project);
    MojoExecution execution = newMojoExecution(execName);
    Mojo mojo = lookupConfiguredMojo(session, execution);
    assertNotNull(mojo);
    return clazz.cast(mojo);
}
 
Example 22
Source Project: vertx-maven-plugin   Source File: MojoExecutor.java    License: Apache License 2.0 5 votes vote down vote up
public MojoExecutor(MojoExecution execution, MavenProject project, MavenSession session, BuildPluginManager buildPluginManager) {
    this.build = buildPluginManager;
    this.project = project;
    this.session = session;
    this.plugin = execution.getPlugin();
    configuration = execution.getConfiguration();
    goal = execution.getGoal();
}
 
Example 23
Source Project: vertx-maven-plugin   Source File: MojoUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute the Maven Compiler Plugin to compile java sources.
 *
 * @param project            the project
 * @param mavenSession       the session
 * @param buildPluginManager the build plugin manager
 * @throws Exception if the compilation fails for any reason
 */
public static void compile(MavenProject project, MavenSession mavenSession,
                           BuildPluginManager buildPluginManager) throws Exception {

    Optional<Plugin> mvnCompilerPlugin = project.getBuildPlugins().stream()
        .filter(plugin -> A_MAVEN_COMPILER_PLUGIN.equals(plugin.getArtifactId()))
        .findFirst();

    String pluginVersion = properties.getProperty(V_MAVEN_COMPILER_PLUGIN);

    if (mvnCompilerPlugin.isPresent()) {
        pluginVersion = mvnCompilerPlugin.get().getVersion();
    }

    Optional<Xpp3Dom> optConfiguration = buildConfiguration(project, A_MAVEN_COMPILER_PLUGIN, GOAL_COMPILE);

    if (optConfiguration.isPresent()) {

        Xpp3Dom configuration = optConfiguration.get();

        executeMojo(
            plugin(G_MAVEN_COMPILER_PLUGIN, A_MAVEN_COMPILER_PLUGIN, pluginVersion),
            goal(GOAL_COMPILE),
            configuration,
            executionEnvironment(project, mavenSession, buildPluginManager)
        );
    }
}
 
Example 24
Source Project: vertx-maven-plugin   Source File: MojoUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Executes the Maven Resource Plugin to copy resources to `target/classes`
 *
 * @param project            the project
 * @param mavenSession       the maven session
 * @param buildPluginManager the build plugin manager
 * @throws MojoExecutionException if the copy cannot be completed successfully
 */
public static void copyResources(MavenProject project, MavenSession mavenSession,
                                 BuildPluginManager buildPluginManager) throws MojoExecutionException {

    Optional<Plugin> resourcesPlugin = hasPlugin(project, RESOURCES_PLUGIN_KEY);

    Xpp3Dom pluginConfig = configuration(element("outputDirectory", "${project.build.outputDirectory}"));

    if (resourcesPlugin.isPresent()) {

        Optional<Xpp3Dom> optConfiguration = buildConfiguration(project, A_MAVEN_RESOURCES_PLUGIN, GOAL_RESOURCES);

        if (optConfiguration.isPresent()) {
            pluginConfig = optConfiguration.get();
        }

        executeMojo(
            resourcesPlugin.get(),
            goal(GOAL_RESOURCES),
            pluginConfig,
            executionEnvironment(project, mavenSession, buildPluginManager)
        );

    } else {
        executeMojo(
            plugin(G_MAVEN_RESOURCES_PLUGIN, A_MAVEN_RESOURCES_PLUGIN,
                properties.getProperty(V_MAVEN_RESOURCES_PLUGIN)),
            goal(GOAL_RESOURCES),
            pluginConfig,
            executionEnvironment(project, mavenSession, buildPluginManager)
        );
    }

}
 
Example 25
Source Project: java-specialagent   Source File: MutableMojo.java    License: Apache License 2.0 5 votes vote down vote up
private static Object getRepositorySystemSession(final MavenSession session) {
  try {
    final Field field = session.getClass().getDeclaredField("repositorySession");
    field.setAccessible(true);
    return field.get(session);
  }
  catch (final IllegalAccessException | NoSuchFieldException e) {
    throw new RuntimeException(e);
  }
}
 
Example 26
private Reader getFilteredReader(File path, MavenProject project, MavenSession session) throws FileNotFoundException, MavenFilteringException {
    MavenReaderFilterRequest request =
        new MavenReaderFilterRequest(
            new FileReader(path),
            true,
            project,
            Collections.<String>emptyList(),
            false,
            session,
            null);
    //request.setEscapeString("$");
    return readerFilter.filter(request);
}
 
Example 27
Source Project: smart-testing   Source File: SkipInstallationCheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void checker_should_return_false_when_plugin_goal_set_set() {
    // given
    MavenSession mavenSession = setUpMavenSession(
        Arrays.asList("clean", "org.apache.maven.plugins:maven-surefire-plugin:2.20.1:test"), null);

    // when
    SkipInstallationChecker skipInstallationChecker = new SkipInstallationChecker(mavenSession);

    // then
    softly.assertThat(skipInstallationChecker).isSkipped(false);
}
 
Example 28
@Test
public void testCustomTestPropertiesFile() throws Exception {
  File basedir = resources.getBasedir("testproperties/custom-test-properties-file");
  MavenProject project = mojos.readMavenProject(basedir);
  MavenSession session = mojos.newMavenSession(project);

  mojos.executeMojo(session, project, newMojoExecution());
  Assert.assertEquals("value", readProperties(basedir).get("custom"));

  TestResources.cp(basedir, "src/test/modified-test.properties", "src/test/test.properties");
  mojos.executeMojo(session, project, newMojoExecution());
  Assert.assertEquals("modified-value", readProperties(basedir).get("custom"));
}
 
Example 29
Source Project: neoscada   Source File: QualifierNameProvider.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public Configuration ( final MavenSession session, final MojoExecution execution, final MavenProject project, final Map<String, String> properties )
{
    this.session = session;
    this.execution = execution;
    this.project = project;
    this.properties = properties;
}
 
Example 30
Source Project: smart-testing   Source File: SkipInstallationCheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void checker_should_return_false_when_classes_and_pattern_are_set() {
    // given
    MavenSession mavenSession = getMavenSessionForProperty("test", "FirstTest,MyCool*Test,LastTest");

    // when
    SkipInstallationChecker skipInstallationChecker = new SkipInstallationChecker(mavenSession);

    // then
    softly.assertThat(skipInstallationChecker).isSkipped(false);
}