Example usage for org.apache.maven.execution MavenSession getCurrentProject

List of usage examples for org.apache.maven.execution MavenSession getCurrentProject

Introduction

In this page you can find the example usage for org.apache.maven.execution MavenSession getCurrentProject.

Prototype

public MavenProject getCurrentProject() 

Source Link

Usage

From source file:com.carrotgarden.m2e.config.ConfigBuildParticipant.java

License:BSD License

/**
 * @see <a href=/*from  ww  w  .  ja v  a  2s  .co m*/
 *      "https://github.com/sonatype/sisu-build-api/tree/master/src/main/java/org/sonatype/plexus/build/incremental"
 *      />
 */
@Override
public Set<IProject> build(final int kind, final IProgressMonitor monitor) throws Exception {

    final BuildContext buildContext = getBuildContext();
    final MavenSession session = getSession();
    final MojoExecution execution = getMojoExecution();
    final MavenProject project = session.getCurrentProject();

    //

    log.info("### project : {}", project);
    log.info("### execution : {}", execution);
    log.info("### incremental : {}", buildContext.isIncremental());

    //

    final List<String> sourceRoots = project.getCompileSourceRoots();

    if (!MojoUtil.isValid(sourceRoots)) {
        log.warn("### not valid source roots");
        return NOOP;
    }

    int countSCR = 0;
    int countBND = 0;

    for (final String rootPath : sourceRoots) {

        if (!MojoUtil.isValid(rootPath)) {
            log.warn("### not valid root path");
            continue;
        }

        log.debug("### rootPath : {}", rootPath);

        final File rootDir = new File(rootPath);

        final Scanner scanner = buildContext.newScanner(rootDir);

        scanner.scan();

        final String[] includedFiles = scanner.getIncludedFiles();

        if (!MojoUtil.isValid(includedFiles)) {
            log.warn("### not valid included files");
            continue;
        }

        for (final String relativePath : includedFiles) {

            final File file = new File(rootDir, relativePath);

            log.debug("### file : {}", file);

            if (MojoUtil.isInterestSCR(file)) {
                countSCR++;
            }

            if (MojoUtil.isInterestBND(file)) {
                countBND++;
            }

        }

    }

    final MavenContext context = new MavenContext(session, execution);

    final boolean hasSCR = countSCR > 0 && MojoUtil.isMojoSCR(context);
    final boolean hasBND = countBND > 0 && MojoUtil.isMojoBND(context);

    if (hasSCR || hasBND) {

        final String key = context.getKey();

        // MavenJob job = (MavenJob) buildContext.getValue(key);
        MavenJob job = jobMap.get(key);

        if (job == null) {
            job = new MavenJob(context);
            // buildContext.setValue(key, job);
            jobMap.put(key, job);
        }

        job.schedule();

        log.info("### job scheduled");

    } else {

        log.warn("### no interesting files");

    }

    return NOOP;

}

From source file:com.doublefx.maven.utils.flexmojos.mavenValidator.FlexMojosExtensionInstallationHelper.java

License:Apache License

protected void copyExtension(MavenSession session, String artifactCoordinates) throws MavenExecutionException {
    Artifact artifact;/*from  w ww  . j  a  v  a2s. c  o  m*/
    try {
        artifact = new DefaultArtifact(artifactCoordinates);
    } catch (IllegalArgumentException e) {
        throw newMavenExecutionException(e);
    }

    ArtifactRequest request = new ArtifactRequest();
    request.setArtifact(artifact);

    final List<RemoteRepository> remoteRepos = session.getCurrentProject().getRemoteProjectRepositories();

    request.setRepositories(remoteRepos);

    ArtifactResult result;
    try {
        result = repoSystem.resolveArtifact(session.getRepositorySession(), request);
    } catch (ArtifactResolutionException e) {
        logger.info("Resolving artifact " + artifact + " from " + remoteRepos);
        throw newMavenExecutionException(e);
    }

    final Artifact resultArtifact = result.getArtifact();

    final String maven_home = System.getenv("MAVEN_HOME");
    final File destination = new File(maven_home + File.separator + "lib" + File.separator + "ext"
            + File.separator + resultArtifact.getArtifactId() + ".jar");

    if (!destination.exists()) {
        logger.info("Resolved artifact " + artifact + " to " + resultArtifact.getFile() + " from "
                + result.getRepository());

        try {
            Files.copy(resultArtifact.getFile().toPath(), destination.toPath());
        } catch (IOException ignored) {
        }

        logger.info(
                resultArtifact.getArtifactId() + " is now configured, it will be applied to your next builds.");
    }
}

From source file:com.github.shyiko.sme.ServersExtension.java

License:Apache License

/**
 * Lookup for property name in maven project.
 *
 * @param session current maven session/*from   ww w .j a  va2  s  . c om*/
 * @param propName property name
 * @return true is property is set and has value "true"
 */
private boolean isExtensionProperty(MavenSession session, String propName) {
    Properties properties = session.getUserProperties();
    String value = properties.getProperty(propName);
    if (value != null) {
        return Boolean.valueOf(value);
    }

    properties = session.getCurrentProject().getProperties();
    value = properties.getProperty(propName);
    return Boolean.valueOf(value);
}

From source file:com.github.shyiko.ump.NonRecursiveExtension.java

License:Apache License

public void afterProjectsRead(MavenSession session) {
    if (session.getGoals().isEmpty() && session.getUserProperties().isEmpty()) {
        session.setProjects(Arrays.asList(session.getTopLevelProject()));
        if (session.getCurrentProject().getDefaultGoal() == null) {
            session.getGoals().add("usage:show");
        }/*w  w  w  .  ja v  a  2  s .  c  o  m*/
    }
}

From source file:com.googlecode.ounit.maven.ReflectiveSurefireReportParser.java

License:Open Source License

public ReflectiveSurefireReportParser(MavenSession session, BuildPluginManager pluginManager) throws Exception {

    // TODO: Utter a warning if surefire used in build is different from surefire used for reporting
    /*/*from w  w  w  .  j av a 2s . c  o  m*/
    MavenProject project = session.getCurrentProject();
    for (Plugin p : project.getBuildPlugins()) {
       if (p.getId().startsWith("org.apache.maven.plugins:maven-surefire-plugin")) {
    System.out.println("Surefire version in project: "
          + p.getVersion());
    System.out.println("Surefire conf: "
          + p.getConfiguration().toString());
       }
    }
    */

    String sfGrId = "org.apache.maven.plugins";
    String sfVer = "2.8.1";

    Plugin plugin = new Plugin();
    plugin.setGroupId(sfGrId);
    plugin.setArtifactId("maven-surefire-report-plugin");
    plugin.setVersion(sfVer);
    PluginDescriptor pluginDescriptor = pluginManager.loadPlugin(plugin,
            session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession());
    parserClass = pluginManager.getPluginRealm(session, pluginDescriptor)
            .loadClass("org.apache.maven.plugins.surefire.report.SurefireReportParser");
    testCaseClass = pluginManager.getPluginRealm(session, pluginDescriptor)
            .loadClass("org.apache.maven.plugins.surefire.report.ReportTestCase");
}

From source file:com.jayway.maven.plugins.android.phase_prebuild.AarMavenLifecycleParticipant.java

License:Open Source License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    log.debug("");
    log.debug("AMLP afterProjectsRead");
    log.debug("");

    log.debug("CurrentProject=" + session.getCurrentProject());
    final List<MavenProject> projects = session.getProjects();

    for (MavenProject project : projects) {
        log.debug("");
        log.debug("project=" + project.getArtifact());

        final BuildHelper helper = new BuildHelper(repoSystem, session.getRepositorySession(), project, log);

        final Collection<Artifact> artifacts = getProjectsArtifacts(session, project);
        log.debug("projects deps: : " + artifacts);
        for (Artifact artifact : artifacts) {
            final String type = artifact.getType();
            if (type.equals(AndroidExtension.AAR)) {
                // An AAR lib contains a classes jar that needs to be added to the classpath.
                // Create a placeholder classes.jar and add it to the compile classpath.
                // It will replaced with the real classes.jar by GenerateSourcesMojo.
                addClassesToClasspath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APK)) {
                // The only time that an APK will likely be a dependency is when this an an APK test project.
                // So add a placeholder (we cannot resolve the actual dep pre build) to the compile classpath.
                // The placeholder will be replaced with the real APK jar later.
                addClassesToClasspath(helper, project, artifact);
            }/*  w  w  w. j av a  2  s  .co m*/
        }
    }
}

From source file:com.jayway.maven.plugins.android.phase_prebuild.ClasspathModifierLifecycleParticipant.java

License:Open Source License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - start");
    log.debug("");

    log.debug("CurrentProject=" + session.getCurrentProject());
    final List<MavenProject> projects = session.getProjects();
    final DependencyResolver dependencyResolver = new DependencyResolver(log, dependencyGraphBuilder);
    final ArtifactResolverHelper artifactResolverHelper = new ArtifactResolverHelper(artifactResolver, log);

    for (MavenProject project : projects) {
        log.debug("");
        log.debug("project=" + project.getArtifact());

        if (!AndroidExtension.isAndroidPackaging(project.getPackaging())) {
            continue; // do not modify classpath if not an android project.
        }/*  ww  w .ja  v a2  s .  co m*/

        final UnpackedLibHelper helper = new UnpackedLibHelper(artifactResolverHelper, project, log);

        final Set<Artifact> artifacts;

        // If there is an extension ClassRealm loaded for this project then use that
        // as the ContextClassLoader so that Wagon extensions can be used to resolves dependencies.
        final ClassLoader projectClassLoader = (project.getClassRealm() != null) ? project.getClassRealm()
                : Thread.currentThread().getContextClassLoader();

        final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(projectClassLoader);
            artifacts = dependencyResolver.getProjectDependenciesFor(project, session);
        } catch (DependencyGraphBuilderException e) {
            // Nothing to do. The resolution failure will be displayed by the standard resolution mechanism.
            continue;
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }

        log.debug("projects deps: : " + artifacts);
        for (Artifact artifact : artifacts) {
            final String type = artifact.getType();
            if (type.equals(AndroidExtension.AAR)) {
                // An AAR lib contains a classes jar that needs to be added to the classpath.
                // Create a placeholder classes.jar and add it to the compile classpath.
                // It will replaced with the real classes.jar by GenerateSourcesMojo.
                addClassesToClasspath(helper, project, artifact);
                // Add jar files in 'libs' into classpath.
                addLibsJarsToClassPath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APK)) {
                // The only time that an APK will likely be a dependency is when this an an APK test project.
                // So add a placeholder (we cannot resolve the actual dep pre build) to the compile classpath.
                // The placeholder will be replaced with the real APK jar later.
                addClassesToClasspath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APKLIB)) {
                // Add jar files in 'libs' into classpath.
                addLibsJarsToClassPath(helper, project, artifact);
            }
        }
    }
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - finish");
}

From source file:com.photon.maven.plugins.android.AbstractAndroidMojoTestCase.java

License:Apache License

/**
 * Copy the project specified into a temporary testing directory. Create the {@link MavenProject} and
 * {@link ManifestUpdateMojo}, configure it from the <code>plugin-config.xml</code> and return the created Mojo.
 * <p>//from  ww  w  . j ava  2  s  . c o m
 * Note: only configuration entries supplied in the plugin-config.xml are presently configured in the mojo returned.
 * That means and 'default-value' settings are not automatically injected by this testing framework (or plexus
 * underneath that is suppling this functionality)
 * 
 * @param resourceProject
 *            the name of the goal to look for in the <code>plugin-config.xml</code> that the configuration will be
 *            pulled from.
 * @param resourceProject
 *            the resourceProject path (in src/test/resources) to find the example/test project.
 * @return the created mojo (unexecuted)
 * @throws Exception
 *             if there was a problem creating the mojo.
 */
protected T createMojo(String resourceProject) throws Exception {
    // Establish test details project example
    String testResourcePath = "src/test/resources/" + resourceProject;
    testResourcePath = FilenameUtils.separatorsToSystem(testResourcePath);
    File exampleDir = new File(getBasedir(), testResourcePath);
    Assert.assertTrue("Path should exist: " + exampleDir, exampleDir.exists());

    // Establish the temporary testing directory.
    String testingPath = "target/tests/" + this.getClass().getSimpleName() + "." + getName();
    testingPath = FilenameUtils.separatorsToSystem(testingPath);
    File testingDir = new File(getBasedir(), testingPath);

    if (testingDir.exists()) {
        FileUtils.cleanDirectory(testingDir);
    } else {
        Assert.assertTrue("Could not create directory: " + testingDir, testingDir.mkdirs());
    }

    // Copy project example into temporary testing directory
    // to avoid messing up the good source copy, as mojo can change
    // the AndroidManifest.xml file.
    FileUtils.copyDirectory(exampleDir, testingDir);

    // Prepare MavenProject
    final MavenProject project = new MojoProjectStub(testingDir);

    // Setup Mojo
    PlexusConfiguration config = extractPluginConfiguration("android-maven-plugin", project.getFile());
    @SuppressWarnings("unchecked")
    final T mojo = (T) lookupMojo(getPluginGoalName(), project.getFile());

    // Inject project itself
    setVariableValueToObject(mojo, "project", project);

    // Configure the rest of the pieces via the PluginParameterExpressionEvaluator
    //  - used for ${plugin.*}
    MojoDescriptor mojoDesc = new MojoDescriptor();
    // - used for error messages in PluginParameterExpressionEvaluator
    mojoDesc.setGoal(getPluginGoalName());
    MojoExecution mojoExec = new MojoExecution(mojoDesc);
    // - Only needed if we start to use expressions like ${settings.*}, ${localRepository}, ${reactorProjects}
    // MavenSession context = null; // Messy to declare, would rather avoid using it.
    // - Used for ${basedir} relative paths
    PathTranslator pathTranslator = new DefaultPathTranslator();
    // - Declared to prevent NPE from logging events in maven core
    Logger logger = new ConsoleLogger(Logger.LEVEL_DEBUG, mojo.getClass().getName());

    MavenSession context = createMock(MavenSession.class);

    expect(context.getExecutionProperties()).andReturn(project.getProperties());
    expect(context.getCurrentProject()).andReturn(project);
    replay(context);

    // Declare evalator that maven itself uses.
    ExpressionEvaluator evaluator = new PluginParameterExpressionEvaluator(context, mojoExec, pathTranslator,
            logger, project, project.getProperties());
    // Lookup plexus configuration component
    ComponentConfigurator configurator = (ComponentConfigurator) lookup(ComponentConfigurator.ROLE, "basic");
    // Configure mojo using above
    ConfigurationListener listener = new DebugConfigurationListener(logger);
    configurator.configureComponent(mojo, config, evaluator, getContainer().getContainerRealm(), listener);

    return mojo;
}

From source file:com.simpligility.maven.plugins.android.phase_prebuild.ClasspathModifierLifecycleParticipant.java

License:Open Source License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - start");
    log.debug("");

    log.debug("CurrentProject=" + session.getCurrentProject());
    final List<MavenProject> projects = session.getProjects();
    final DependencyResolver dependencyResolver = new DependencyResolver(log, dependencyGraphBuilder);
    final ArtifactResolverHelper artifactResolverHelper = new ArtifactResolverHelper(artifactResolver, log);

    for (MavenProject project : projects) {
        log.debug("");
        log.debug("project=" + project.getArtifact());

        if (!AndroidExtension.isAndroidPackaging(project.getPackaging())) {
            continue; // do not modify classpath if not an android project.
        }//w w  w .j av a2 s  .  c  om

        final String unpackedLibsFolder = getMojoConfigurationParameter(project, UNPACKED_LIBS_FOLDER_PARAM,
                null);
        final UnpackedLibHelper helper = new UnpackedLibHelper(artifactResolverHelper, project, log,
                unpackedLibsFolder == null ? null : new File(unpackedLibsFolder));

        final Set<Artifact> artifacts;

        // If there is an extension ClassRealm loaded for this project then use that
        // as the ContextClassLoader so that Wagon extensions can be used to resolves dependencies.
        final ClassLoader projectClassLoader = (project.getClassRealm() != null) ? project.getClassRealm()
                : Thread.currentThread().getContextClassLoader();

        final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(projectClassLoader);
            artifacts = dependencyResolver.getProjectDependenciesFor(project, session);
        } catch (DependencyGraphBuilderException e) {
            // Nothing to do. The resolution failure will be displayed by the standard resolution mechanism.
            continue;
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }

        boolean includeFromAar = getMojoConfigurationParameter(project, INCLUDE_FROM_AAR_PARAM,
                INCLUDE_FROM_AAR_DEFAULT);
        boolean includeFromApklib = getMojoConfigurationParameter(project, INCLUDE_FROM_APKLIB_PARAM,
                INCLUDE_FROM_APKLIB_DEFAULT);
        boolean disableConflictingDependenciesWarning = getMojoConfigurationParameter(project,
                DISABLE_CONFLICTING_DEPENDENCIES_WARNING_PARAM,
                DISABLE_CONFLICTING_DEPENDENCIES_WARNING_DEFAULT);

        log.debug("projects deps: : " + artifacts);

        if (!disableConflictingDependenciesWarning) {
            ProvidedDependencyChecker checker = new ProvidedDependencyChecker();
            checker.checkProvidedDependencies(artifacts, log);
        }

        for (Artifact artifact : artifacts) {
            final String type = artifact.getType();
            if (type.equals(AndroidExtension.AAR)) {
                // An AAR lib contains a classes jar that needs to be added to the classpath.
                // Create a placeholder classes.jar and add it to the compile classpath.
                // It will replaced with the real classes.jar by GenerateSourcesMojo.
                addClassesToClasspath(helper, project, artifact);

                // An AAR may also contain zero or more internal libs in the libs folder.
                // If 'includeLibsJarsFromAar' config param is true then include them too.
                if (includeFromAar) {
                    // Add jar files in 'libs' into classpath.
                    addLibsJarsToClassPath(helper, project, artifact);
                }
            } else if (type.equals(AndroidExtension.APK)) {
                // The only time that an APK will likely be a dependency is when this an an APK test project.
                // So add a placeholder (we cannot resolve the actual dep pre build) to the compile classpath.
                // The placeholder will be replaced with the real APK jar later.
                addClassesToClasspath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APKLIB)) {
                if (includeFromApklib) {
                    // Add jar files in 'libs' into classpath.
                    addLibsJarsToClassPath(helper, project, artifact);
                }
            }
        }
    }

    if (addedJarFromLibs) {
        log.warn("Transitive dependencies should really be provided by Maven dependency management.\n"
                + "          We suggest you to ask the above providers to package their component properly.\n"
                + "          Things may break at compile and/or runtime due to multiple copies of incompatible libraries.");
    }
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - finish");
}

From source file:com.soebes.maven.extensions.incremental.IncrementalModuleBuilder.java

License:Apache License

@Override
public void build(final MavenSession session, final ReactorContext reactorContext,
        ProjectBuildList projectBuilds, final List<TaskSegment> taskSegments,
        ReactorBuildStatus reactorBuildStatus) throws ExecutionException, InterruptedException {

    // Think about this?
    if (!session.getCurrentProject().isExecutionRoot()) {
        LOGGER.info("Not executing in root.");
    }// w ww  .ja  v a  2 s  .c om

    Path projectRootpath = session.getTopLevelProject().getBasedir().toPath();

    if (!havingScmDeveloperConnection(session)) {
        LOGGER.warn("There is no scm developer connection configured.");
        LOGGER.warn("So we can't estimate which modules have changed.");
        return;
    }

    // TODO: Make more separation of concerns..(Extract the SCM Code from
    // here?
    ScmRepository repository = null;
    try {
        // Assumption: top level project contains the SCM entry.
        repository = scmManager
                .makeScmRepository(session.getTopLevelProject().getScm().getDeveloperConnection());
    } catch (ScmRepositoryException | NoSuchScmProviderException e) {
        LOGGER.error("Failure during makeScmRepository", e);
        return;
    }

    StatusScmResult result = null;
    try {
        result = scmManager.status(repository, new ScmFileSet(session.getTopLevelProject().getBasedir()));
    } catch (ScmException e) {
        LOGGER.error("Failure during status", e);
        return;
    }

    List<ScmFile> changedFiles = result.getChangedFiles();
    if (changedFiles.isEmpty()) {
        LOGGER.info(" Nothing has been changed.");
    } else {

        for (ScmFile scmFile : changedFiles) {
            LOGGER.info(" Changed file: " + scmFile.getPath() + " " + scmFile.getStatus());
        }

        ModuleCalculator mc = new ModuleCalculator(session.getProjectDependencyGraph().getSortedProjects(),
                changedFiles);
        List<MavenProject> calculateChangedModules = mc.calculateChangedModules(projectRootpath);

        for (MavenProject mavenProject : calculateChangedModules) {
            LOGGER.info("Changed Project: " + mavenProject.getId());
        }

        IncrementalModuleBuilderImpl incrementalModuleBuilderImpl = new IncrementalModuleBuilderImpl(
                calculateChangedModules, lifecycleModuleBuilder, session, reactorContext, taskSegments);

        // Really build only changed modules.
        incrementalModuleBuilderImpl.build();
    }
}