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

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

Introduction

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

Prototype

public void setProjects(List<MavenProject> projects) 

Source Link

Usage

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 .  j  av  a  2  s. c o m*/
    }
}

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>();
        }//from  w  w  w.j a  v  a 2  s .  c o  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);//from  ww  w  . j  a  v a  2 s.  c  o m
    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/*  w  w  w .  j  a  va  2 s . c o  m*/
protected MavenSession newMavenSession(MavenProject project) {
    MavenSession session = newMavenSession();
    session.setCurrentProject(project);
    session.setProjects(Arrays.asList(project));
    return session;
}

From source file:fr.fastconnect.factory.tibco.bw.maven.BWLifecycleParticipant.java

License:Apache License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    logger.debug("BW lifecycle participant");

    propertiesManager = AbstractBWMojo.propertiesManager(session, session.getCurrentProject());

    List<MavenProject> projects = prepareProjects(session.getProjects(), session);
    session.setProjects(projects);
}

From source file:io.sundr.maven.GenerateBomMojo.java

License:Apache License

private void build(MavenSession session, MavenProject project, List<MavenProject> allProjects, GoalSet goals)
        throws MojoExecutionException {
    session.setProjects(allProjects);
    ProjectIndex projectIndex = new ProjectIndex(session.getProjects());
    try {/*from  w  w w  .  ja  v  a  2s.co  m*/
        ReactorBuildStatus reactorBuildStatus = new ReactorBuildStatus(
                new BomDependencyGraph(session.getProjects()));
        ReactorContext reactorContext = new ReactorContextFactory(new MavenVersion(mavenVersion)).create(
                session.getResult(), projectIndex, Thread.currentThread().getContextClassLoader(),
                reactorBuildStatus, builder);
        List<TaskSegment> segments = segmentCalculator.calculateTaskSegments(session);
        for (TaskSegment segment : segments) {
            builder.buildProject(session, reactorContext, project, filterSegment(segment, goals));
        }
    } catch (Throwable t) {
        throw new MojoExecutionException("Error building generated bom:" + project.getArtifactId(), t);
    }
}

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 .ja  v  a  2s  .  com
@Override
protected MavenSession newMavenSession(MavenProject project) {
    MavenSession session = newMavenSession();
    session.setCurrentProject(project);
    session.setProjects(Collections.singletonList(project));
    return session;
}

From source file:net.java.jpatch.maven.common.AbstractMavenMojo.java

License:Apache License

/**
 * Creates the MAVEN session.//ww  w .j a  v  a 2 s .  co m
 * 
 * @return the MAVEN session.
 */
protected MavenSession createMavenSession(List<MavenProject> mavenProjects) {
    JPatchLogger jpatchLogger = new JPatchLogger(getLog());
    ExecutionListener listener = new ExecutionEventLogger(jpatchLogger);
    MavenExecutionRequest execRequest = new DefaultMavenExecutionRequest();
    execRequest.setStartTime(new Date());
    execRequest.setExecutionListener(listener);

    MavenExecutionResult execResult = new DefaultMavenExecutionResult();
    MavenSession result = new MavenSession(null, null, execRequest, execResult);
    result.setProjects(mavenProjects);
    return result;
}

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);/*from ww w .  j a  va 2s. co  m*/
            } finally {
                Thread.currentThread().setContextClassLoader(currentClassLoader);
            }
        }
    }
}

From source file:org.eclipse.m2e.core.internal.embedder.MavenImpl.java

License:Open Source License

@SuppressWarnings("deprecation")
public MavenSession createSession(MavenExecutionRequest request, MavenProject project) {
    RepositorySystemSession repoSession = createRepositorySession(request);
    MavenExecutionResult result = new DefaultMavenExecutionResult();
    MavenSession mavenSession = new MavenSession(plexus, repoSession, request, result);
    if (project != null) {
        mavenSession.setProjects(Collections.singletonList(project));
    }/* ww  w.j  a  v a2s.  c om*/
    return mavenSession;
}