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

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

Introduction

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

Prototype

public void setCurrentProject(MavenProject currentProject) 

Source Link

Usage

From source file:com.google.code.play2.plugin.MavenPlay2Builder.java

License:Apache License

@Override /* Play2Builder */
public boolean build() throws Play2BuildFailure, Play2BuildError/*Play2BuildException*/
{
    Set<String> changedFilePaths = null;
    Map<String, Long> prevChangedFiles = new HashMap<String, Long>();
    synchronized (changedFilesLock) {
        if (!changedFiles.isEmpty()) {
            changedFilePaths = changedFiles.keySet();
            prevChangedFiles = changedFiles;
            changedFiles = new HashMap<String, Long>();
        }//w w  w .  ja va2 s.co  m
        //TEST - more code inside synchronized block
    }

    if (!forceReloadNextTime && changedFilePaths == null /*&& afterFirstSuccessfulBuild*/ ) {
        return false;
    }

    List<MavenProject> projectsToBuild = projects;
    // - !afterFirstSuccessfulBuild => first build or no previous successful builds, build all modules
    // - currentSourceMaps.isEmpty() => first build, build all modules
    // - projects.size() == 1 => one-module project, just build it
    // - else => not the first build in multimodule-project, calculate modules subset to build
    if (afterFirstSuccessfulBuild
            /*!currentSourceMaps.isEmpty()*//*currentSourceMap != null*/ && projects.size() > 1) {
        projectsToBuild = calculateProjectsToBuild(changedFilePaths);
    }

    MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest());
    request.setStartTime(new Date());
    request.setExecutionListener(new ExecutionEventLogger());
    request.setGoals(goals);

    MavenExecutionResult result = new DefaultMavenExecutionResult();

    MavenSession newSession = new MavenSession(container, session.getRepositorySession(), request, result);
    newSession.setProjects(projectsToBuild);
    newSession.setCurrentProject(session.getCurrentProject());
    newSession.setParallel(session.isParallel());
    newSession.setProjectDependencyGraph(session.getProjectDependencyGraph());

    lifecycleExecutor.execute(newSession);

    forceReloadNextTime = result.hasExceptions();

    if (!result.hasExceptions() && !additionalGoals.isEmpty()) {
        request = DefaultMavenExecutionRequest.copy(session.getRequest());
        request.setStartTime(new Date());
        request.setExecutionListener(new ExecutionEventLogger());
        request.setGoals(additionalGoals);

        result = new DefaultMavenExecutionResult();

        newSession = new MavenSession(container, session.getRepositorySession(), request, result);
        List<MavenProject> onlyMe = Arrays.asList(new MavenProject[] { session.getCurrentProject() });
        newSession.setProjects(onlyMe);
        newSession.setCurrentProject(session.getCurrentProject());
        newSession.setParallel(session.isParallel());
        newSession.setProjectDependencyGraph(session.getProjectDependencyGraph());

        lifecycleExecutor.execute(newSession);

        forceReloadNextTime = result.hasExceptions();
    }

    if (result.hasExceptions()) {
        synchronized (changedFilesLock) {
            changedFiles.putAll(prevChangedFiles); // restore previously changed paths, required for next rebuild
        }
        Throwable firstException = result.getExceptions().get(0);
        if (firstException.getCause() instanceof MojoFailureException) {
            MojoFailureException mfe = (MojoFailureException) firstException.getCause();
            Throwable mfeCause = mfe.getCause();
            if (mfeCause != null) {
                try {
                    Play2BuildException pbe = null;
                    String causeName = mfeCause.getClass().getName();

                    // sbt-compiler exception
                    if (CompilerException.class.getName().equals(causeName)) {
                        pbe = getSBTCompilerBuildException(mfeCause);
                    } else if (AssetCompilationException.class.getName().equals(causeName)
                            || RoutesCompilationException.class.getName().equals(causeName)
                            || TemplateCompilationException.class.getName().equals(causeName)) {
                        pbe = getPlayBuildException(mfeCause);
                    }

                    if (pbe != null) {
                        throw new Play2BuildFailure(pbe, sourceEncoding);
                    }
                    throw new Play2BuildError("Build failed without reporting any problem!"/*?, ce*/ );
                } catch (Play2BuildFailure e) {
                    throw e;
                } catch (Play2BuildError e) {
                    throw e;
                } catch (Exception e) {
                    throw new Play2BuildError(".... , check Maven console");
                }
            }
        }
        throw new Play2BuildError("The compilation task failed, check Maven console"/*?, firstException*/ );
    }

    // no exceptions
    if (!afterFirstSuccessfulBuild) // this was first successful build
    {
        afterFirstSuccessfulBuild = true;

        if (playWatchService != null) {
            // Monitor all existing, not generated (inside output directory) source and resource roots
            List<File> monitoredDirectories = new ArrayList<File>();
            for (MavenProject p : projects) {
                String targetDirectory = p.getBuild().getDirectory();
                for (String sourceRoot : p.getCompileSourceRoots()) {
                    if (!sourceRoot.startsWith(targetDirectory) && new File(sourceRoot).isDirectory()) {
                        monitoredDirectories.add(new File(sourceRoot));
                    }
                }
                for (Resource resource : p.getResources()) {
                    String resourceRoot = resource.getDirectory();
                    if (!resourceRoot.startsWith(targetDirectory) && new File(resourceRoot).isDirectory()) {
                        monitoredDirectories.add(new File(resourceRoot));
                    }
                }
            }
            //TODO - remove roots nested inside another roots (is it possible?)

            try {
                watcher = playWatchService.watch(monitoredDirectories, this);
            } catch (FileWatchException e) {
                logger.warn("File watcher initialization failed. Running without hot-reload functionality.", e);
            }
        }
    }

    Map<MavenProject, Map<String, File>> sourceMaps = new HashMap<MavenProject, Map<String, File>>(
            currentSourceMaps);
    for (MavenProject p : projectsToBuild) {
        Map<String, File> sourceMap = new HashMap<String, File>();
        File classesDirectory = new File(p.getBuild().getOutputDirectory());
        String classesDirectoryPath = classesDirectory.getAbsolutePath() + File.separator;
        File analysisCacheFile = defaultAnalysisCacheFile(p);
        Analysis analysis = sbtAnalysisProcessor.readFromFile(analysisCacheFile);
        for (File sourceFile : analysis.getSourceFiles()) {
            Set<File> sourceFileProducts = analysis.getProducts(sourceFile);
            for (File product : sourceFileProducts) {
                String absolutePath = product.getAbsolutePath();
                if (absolutePath.contains("$")) {
                    continue; // skip inner and object classes
                }
                String relativePath = absolutePath.substring(classesDirectoryPath.length());
                //                    String name = product.getName();
                String name = relativePath.substring(0, relativePath.length() - ".class".length());
                /*if (name.indexOf( '$' ) > 0)
                {
                name = name.substring( 0, name.indexOf( '$' ) );
                }*/
                name = name.replace(File.separator, ".");
                //System.out.println(sourceFile.getPath() + " -> " + name);
                sourceMap.put(name, sourceFile);
            }
            /*String[] definitionNames = analysis.getDefinitionNames( sourceFile );
            Set<String> uniqueDefinitionNames = new HashSet<String>(definitionNames.length);
            for (String definitionName: definitionNames)
            {
            if ( !uniqueDefinitionNames.contains( definitionName ) )
            {
                result.put( definitionName, sourceFile );
            //                        System.out.println( "definitionName:'" + definitionName + "', source:'"
            //                                        + sourceFile.getAbsolutePath() + "'" );
                uniqueDefinitionNames.add( definitionName );
            }
            }*/
        }
        sourceMaps.put(p, sourceMap);
    }
    this.currentSourceMaps = sourceMaps;

    boolean reloadRequired = false;
    for (MavenProject p : projectsToBuild) {
        long lastModifiedTime = 0L;
        Set<String> outputFilePaths = new HashSet<String>();
        File outputDirectory = new File(p.getBuild().getOutputDirectory());
        if (outputDirectory.exists() && outputDirectory.isDirectory()) {
            DirectoryScanner classPathScanner = new DirectoryScanner();
            classPathScanner.setBasedir(outputDirectory);
            classPathScanner.setExcludes(new String[] { assetsPrefix + "**" });
            classPathScanner.scan();
            String[] files = classPathScanner.getIncludedFiles();
            for (String fileName : files) {
                File f = new File(outputDirectory, fileName);
                outputFilePaths.add(f.getAbsolutePath());
                long lmf = f.lastModified();
                if (lmf > lastModifiedTime) {
                    lastModifiedTime = lmf;
                }
            }
        }
        if (!reloadRequired && (lastModifiedTime > currentClasspathTimestamps.get(p).longValue()
                || !outputFilePaths.equals(currentClasspathFilePaths.get(p)))) {
            reloadRequired = true;
        }
        currentClasspathTimestamps.put(p, Long.valueOf(lastModifiedTime));
        currentClasspathFilePaths.put(p, outputFilePaths);
    }

    return reloadRequired;
}

From source file:com.puppetlabs.geppetto.forge.maven.plugin.AbstractForgeTestMojo.java

License:Open Source License

protected MavenSession newMavenSession(MavenProject project) {
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    MavenExecutionResult result = new DefaultMavenExecutionResult();

    MavenSession session = new MavenSession(container, new MavenRepositorySystemSession(), request, result);
    session.setCurrentProject(project);
    session.setProjects(Arrays.asList(project));
    return session;
}

From source file:com.ruleoftech.markdown.page.generator.plugin.BetterAbstractMojoTestCase.java

/** Extends the super to use the new {@link #newMavenSession()} introduced here 
 * which sets the defaults one expects from maven; the standard test case leaves a lot of things blank */
@Override//from www.ja v  a2 s .co m
protected MavenSession newMavenSession(MavenProject project) {
    MavenSession session = newMavenSession();
    session.setCurrentProject(project);
    session.setProjects(Arrays.asList(project));
    return session;
}

From source file:io.swagger.v3.plugin.maven.BetterAbstractMojoTestCase.java

/**
 * Extends the super to use the new {@link #newMavenSession()} introduced here
 * which sets the defaults one expects from maven; the standard test case leaves a lot of things blank
 *///from   w ww.  j  a va2  s .c o  m
@Override
protected MavenSession newMavenSession(MavenProject project) {
    MavenSession session = newMavenSession();
    session.setCurrentProject(project);
    session.setProjects(Collections.singletonList(project));
    return session;
}

From source file:org.eclipse.che.maven.server.MavenServerImpl.java

License:Open Source License

private void loadExtensions(MavenProject project, List<Exception> exceptions) {
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    Collection<AbstractMavenLifecycleParticipant> participants = getLifecycleParticipants(
            Collections.singletonList(project));
    if (!participants.isEmpty()) {
        LegacySupport legacySupport = getMavenComponent(LegacySupport.class);
        MavenSession session = legacySupport.getSession();
        session.setCurrentProject(project);
        session.setProjects(Collections.singletonList(project));

        for (AbstractMavenLifecycleParticipant participant : participants) {
            Thread.currentThread().setContextClassLoader(participant.getClass().getClassLoader());
            try {
                participant.afterProjectsRead(session);
            } catch (MavenExecutionException e) {
                exceptions.add(e);/*w w w  . j  a  va  2s.  co m*/
            } finally {
                Thread.currentThread().setContextClassLoader(currentClassLoader);
            }
        }
    }
}

From source file:org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.java

License:Open Source License

private MavenProjectFacade readMavenProjectFacade(final IFile pom, DependencyResolutionContext context,
        final MutableProjectRegistry state, final IProgressMonitor monitor) throws CoreException {
    markerManager.deleteMarkers(pom, IMavenConstants.MARKER_POM_LOADING_ID);

    final ResolverConfiguration resolverConfiguration = ResolverConfigurationIO
            .readResolverConfiguration(pom.getProject());

    return execute(state, pom, resolverConfiguration, new ICallable<MavenProjectFacade>() {
        public MavenProjectFacade call(IMavenExecutionContext context, IProgressMonitor monitor)
                throws CoreException {
            MavenProject mavenProject = null;
            MavenExecutionResult mavenResult = null;
            if (pom.isAccessible()) {
                mavenResult = getMaven().readMavenProject(pom.getLocation().toFile(),
                        context.newProjectBuildingRequest());
                mavenProject = mavenResult.getProject();
            }//from  ww w .j  a  v a 2s.  c  o  m

            MarkerUtils.addEditorHintMarkers(markerManager, pom, mavenProject,
                    IMavenConstants.MARKER_POM_LOADING_ID);
            markerManager.addMarkers(pom, IMavenConstants.MARKER_POM_LOADING_ID, mavenResult);
            if (mavenProject == null) {
                return null;
            }

            // don't cache maven session
            getMaven().detachFromSession(mavenProject);

            final MavenSession mavenSession = context.getSession();
            final MavenProject origCurrentProject = mavenSession.getCurrentProject();
            try {
                mavenSession.setCurrentProject(mavenProject);
                Map<String, List<MojoExecution>> executionPlans = calculateExecutionPlans(pom, mavenProject,
                        monitor);

                // create and return new project facade
                MavenProjectFacade mavenProjectFacade = new MavenProjectFacade(ProjectRegistryManager.this, pom,
                        mavenProject, executionPlans, resolverConfiguration);
                return mavenProjectFacade;
            } finally {
                mavenSession.setCurrentProject(origCurrentProject);
            }
        }
    }, monitor);
}

From source file:org.eclipse.tycho.core.maven.utils.PluginRealmHelper.java

License:Open Source License

public void execute(MavenSession session, MavenProject project, Runnable runnable, PluginFilter filter)
        throws MavenExecutionException {
    for (Plugin plugin : project.getBuildPlugins()) {
        if (plugin.isExtensions()) {
            // due to maven classloading model limitations, build extensions plugins cannot share classes
            // since tycho core, i.e. this code, is loaded as a build extension, no other extensions plugin
            // can load classes from tycho core
            // https://cwiki.apache.org/MAVEN/maven-3x-class-loading.html
            continue;
        }/*from  w w  w .j av a 2s . c  o m*/
        try {
            PluginDescriptor pluginDescriptor = pluginManager.getPluginDescriptor(plugin,
                    project.getRemotePluginRepositories(), session.getRepositorySession());

            if (pluginDescriptor != null) {
                if (pluginDescriptor.getArtifactMap().isEmpty()
                        && pluginDescriptor.getDependencies().isEmpty()) {
                    // force plugin descriptor reload to workaround http://jira.codehaus.org/browse/MNG-5212
                    // this branch won't be executed on 3.0.5+, where MNG-5212 is fixed already
                    PluginDescriptorCache.Key descriptorCacheKey = pluginDescriptorCache.createKey(plugin,
                            project.getRemotePluginRepositories(), session.getRepositorySession());
                    pluginDescriptorCache.put(descriptorCacheKey, null);
                    pluginDescriptor = pluginManager.getPluginDescriptor(plugin,
                            project.getRemotePluginRepositories(), session.getRepositorySession());
                }

                if (filter == null || filter.accept(pluginDescriptor)) {
                    ClassRealm pluginRealm;
                    MavenProject oldCurrentProject = session.getCurrentProject();
                    session.setCurrentProject(project);
                    try {
                        pluginRealm = buildPluginManager.getPluginRealm(session, pluginDescriptor);
                    } finally {
                        session.setCurrentProject(oldCurrentProject);
                    }
                    if (pluginRealm != null) {
                        ClassLoader origTCCL = Thread.currentThread().getContextClassLoader();
                        try {
                            Thread.currentThread().setContextClassLoader(pluginRealm);
                            runnable.run();
                        } finally {
                            Thread.currentThread().setContextClassLoader(origTCCL);
                        }
                    }
                }
            }
        } catch (PluginManagerException e) {
            throw newMavenExecutionException(e);
        } catch (PluginResolutionException e) {
            throw newMavenExecutionException(e);
        } catch (PluginDescriptorParsingException e) {
            throw newMavenExecutionException(e);
        } catch (InvalidPluginDescriptorException e) {
            throw newMavenExecutionException(e);
        }
    }

}

From source file:org.eclipse.tycho.testing.AbstractTychoMojoTestCase.java

License:Open Source License

protected MavenSession newMavenSession(MavenProject project, List<MavenProject> projects) throws Exception {
    MavenExecutionRequest request = newMavenExecutionRequest(new File(project.getBasedir(), "pom.xml"));
    MavenExecutionResult result = new DefaultMavenExecutionResult();
    DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
    MavenSession session = new MavenSession(getContainer(), repositorySession, request, result);
    session.setCurrentProject(project);
    session.setProjects(projects);//from  ww w  . j av  a  2s .c  o m
    return session;
}

From source file:org.jetbrains.idea.maven.server.Maven30ServerEmbedderImpl.java

License:Apache License

/**
 * adapted from {@link DefaultMaven#doExecute(MavenExecutionRequest)}
 */// w  ww.j  a v a 2s .  c  om
private void loadExtensions(MavenProject project, List<Exception> exceptions) {
    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    Collection<AbstractMavenLifecycleParticipant> lifecycleParticipants = getLifecycleParticipants(
            Arrays.asList(project));
    if (!lifecycleParticipants.isEmpty()) {
        LegacySupport legacySupport = getComponent(LegacySupport.class);
        MavenSession session = legacySupport.getSession();
        session.setCurrentProject(project);
        session.setProjects(Arrays.asList(project));

        for (AbstractMavenLifecycleParticipant listener : lifecycleParticipants) {
            Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader());
            try {
                listener.afterProjectsRead(session);
            } catch (MavenExecutionException e) {
                exceptions.add(e);
            } finally {
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
    }
}

From source file:org.jszip.maven.RunMojo.java

License:Apache License

private void addOverlayResources(List<MavenProject> reactorProjects, List<Resource> _resources, Artifact a)
        throws PluginConfigurationException, PluginContainerException, IOException, MojoExecutionException {
    List<Resource> resources = new ArrayList<Resource>();
    MavenProject fromReactor = findProject(reactorProjects, a);
    if (fromReactor != null) {
        MavenSession session = this.session.clone();
        session.setCurrentProject(fromReactor);
        Plugin plugin = findThisPluginInProject(fromReactor);

        // we cheat here and use our version of the plugin... but this is less of a cheat than the only
        // other way which is via reflection.
        MojoDescriptor jszipDescriptor = findMojoDescriptor(pluginDescriptor, JSZipMojo.class);

        for (PluginExecution pluginExecution : plugin.getExecutions()) {
            if (!pluginExecution.getGoals().contains(jszipDescriptor.getGoal())) {
                continue;
            }//from   w w w .ja v  a  2  s  .c o  m
            MojoExecution mojoExecution = createMojoExecution(plugin, pluginExecution, jszipDescriptor);
            JSZipMojo mojo = (JSZipMojo) mavenPluginManager.getConfiguredMojo(Mojo.class, session,
                    mojoExecution);
            try {
                File contentDirectory = mojo.getContentDirectory();
                if (contentDirectory.isDirectory()) {
                    getLog().debug("Adding resource directory " + contentDirectory);
                    resources.add(Resource.newResource(contentDirectory));
                }
                // TODO filtering support
                //
                // The good news:
                //  * resources:resources gets the list of resources from /project/build/resources *only*
                // The bad news:
                //  * looks like maven-invoker is the only way to safely invoke it again
                //
                // probable solution
                //
                // 1. get the list of all resource directories, add on the scan for changes
                // 2. if a change to a non-filtered file, just copy it over
                // 3. if a change to a filtered file or a change to effective pom, use maven-invoker to run the
                //    lifecycle up to 'compile' or 'process-resources' <-- preferred
                //
                File resourcesDirectory = mojo.getResourcesDirectory();
                if (resourcesDirectory.isDirectory()) {
                    getLog().debug("Adding resource directory " + resourcesDirectory);
                    resources.add(Resource.newResource(resourcesDirectory));
                }
            } finally {
                mavenPluginManager.releaseMojo(mojo, mojoExecution);
            }
        }
    } else {
        resources.add(Resource.newResource("jar:" + a.getFile().toURI().toURL() + "!/"));
    }

    // TODO support live reloading of mappings
    String path = "";
    if (mappings != null) {
        for (Mapping mapping : mappings) {
            if (mapping.isMatch(a)) {
                path = StringUtils.clean(mapping.getPath());
                break;
            }
        }
    }

    if (StringUtils.isBlank(path)) {
        _resources.addAll(resources);
    } else {
        ResourceCollection child = new ResourceCollection(resources.toArray(new Resource[resources.size()]));
        _resources.add(new VirtualDirectoryResource(child, path));
    }
}