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

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

Introduction

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

Prototype

@Deprecated
    public MavenSession(PlexusContainer container, MavenExecutionRequest request, MavenExecutionResult result,
            List<MavenProject> projects) 

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>();
        }//from   w w  w . ja  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  w w  w .j  av  a2 s  .  c om
    session.setProjects(Arrays.asList(project));
    return session;
}

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

protected MavenSession newMavenSession() {
    try {//  w  ww .  j av a2 s  . c  o  m
        MavenExecutionRequest request = new DefaultMavenExecutionRequest();
        MavenExecutionResult result = new DefaultMavenExecutionResult();

        // populate sensible defaults, including repository basedir and remote repos
        MavenExecutionRequestPopulator populator;
        populator = getContainer().lookup(MavenExecutionRequestPopulator.class);
        populator.populateDefaults(request);

        // this is needed to allow java profiles to get resolved; i.e. avoid during project builds:
        // [ERROR] Failed to determine Java version for profile java-1.5-detected @ org.apache.commons:commons-parent:22, /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, line 909, column 14
        request.setSystemProperties(System.getProperties());

        // and this is needed so that the repo session in the maven session 
        // has a repo manager, and it points at the local repo
        // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done)
        DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class);
        DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) maven
                .newRepositorySession(request);
        repoSession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(repoSession,
                new LocalRepository(request.getLocalRepository().getBasedir())));

        @SuppressWarnings("deprecation")
        MavenSession session = new MavenSession(getContainer(), repoSession, request, result);
        return session;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.vladsch.flexmark.page.generator.plugin.BetterAbstractMojoTestCase.java

protected MavenSession newMavenSession() {
    try {/*ww  w  .  j a v  a  2s  . c om*/
        MavenExecutionRequest request = new DefaultMavenExecutionRequest();
        MavenExecutionResult result = new DefaultMavenExecutionResult();

        // populate sensible defaults, including repository basedir and remote repos
        MavenExecutionRequestPopulator populator;
        populator = getContainer().lookup(MavenExecutionRequestPopulator.class);
        populator.populateDefaults(request);

        // this is needed to allow java profiles to get resolved; i.e. avoid during project builds:
        // [ERROR] Failed to determine Java version for profile java-1.5-detected @ org.apache.commons:commons-parent:22, /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, line 909, column 14
        request.setSystemProperties(System.getProperties());

        // and this is needed so that the repo session in the maven session
        // has a repo manager, and it points at the local repo
        // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done)
        DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class);
        DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) maven
                .newRepositorySession(request);
        repoSession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(repoSession,
                new LocalRepository(request.getLocalRepository().getBasedir())));

        @SuppressWarnings("deprecation")
        MavenSession session = new MavenSession(getContainer(), repoSession, request, result);
        return session;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:hudson.maven.MavenEmbedder.java

License:Apache License

private MavenEmbedder(File mavenHome, MavenRequest mavenRequest, PlexusContainer plexusContainer)
        throws MavenEmbedderException {
    this.mavenHome = mavenHome;
    this.mavenRequest = mavenRequest;
    this.plexusContainer = plexusContainer;

    try {//w w  w  .  j  ava2  s  .  c o m
        this.mavenExecutionRequest = this.buildMavenExecutionRequest(mavenRequest);

        RepositorySystemSession rss = ((DefaultMaven) lookup(Maven.class))
                .newRepositorySession(mavenExecutionRequest);

        mavenSession = new MavenSession(plexusContainer, rss, mavenExecutionRequest,
                new DefaultMavenExecutionResult());

        lookup(LegacySupport.class).setSession(mavenSession);
    } catch (MavenEmbedderException e) {
        throw new MavenEmbedderException(e.getMessage(), e);
    } catch (ComponentLookupException e) {
        throw new MavenEmbedderException(e.getMessage(), e);
    }
}

From source file:info.debatty.sparkpackages.maven.plugin.MojoTestCase.java

License:Open Source License

/**
 * Create an instance of Mojo corresponding to the provided goal.
 * The Mojo will be configured according to values provided in the pom.
 * @param pom//from   w  w w  . j  av  a2s. c o  m
 * @param goal
 * @return
 * @throws Exception if something went wrong...
 */
public final Mojo lookupConfiguredMojo(final File pom, final String goal) throws Exception {

    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    MavenExecutionResult result = new DefaultMavenExecutionResult();

    // populate default values for (a.o.) repository basedir and
    // remote repos
    MavenExecutionRequestPopulator populator = getContainer().lookup(MavenExecutionRequestPopulator.class);
    populator.populateDefaults(request);

    // this is needed to allow java profiles to get resolved;
    // i.e. avoid during project builds:
    // [ERROR] Failed to determine Java version for profile
    // java-1.5-detected
    request.setSystemProperties(System.getProperties());

    // and this is needed so that the repo session in the maven session
    // has a repo manager, and it points at the local repo
    // (cf MavenRepositorySystemUtils.newSession() which is what is
    // otherwise done)
    DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class);
    DefaultRepositorySystemSession repo_session = (DefaultRepositorySystemSession) maven
            .newRepositorySession(request);
    repo_session.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(repo_session,
            new LocalRepository(request.getLocalRepository().getBasedir())));

    @SuppressWarnings("deprecation")
    MavenSession session = new MavenSession(getContainer(), repo_session, request, result);

    ProjectBuildingRequest building_request = session.getProjectBuildingRequest();
    ProjectBuilder project_builder = lookup(ProjectBuilder.class);
    MavenProject project = project_builder.build(pom, building_request).getProject();

    return super.lookupConfiguredMojo(project, goal);

}

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

License:Apache License

/**
 * Creates the MAVEN session./*from w  w w . j  ava 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:net.oneandone.maven.plugins.prerelease.util.IntegrationBase.java

License:Apache License

public static Maven maven(World world) {
    DefaultPlexusContainer container;//from   ww  w . j  a  v  a 2  s  .c  om
    ArtifactRepositoryFactory factory;
    ArtifactRepository central;
    ArtifactRepository snapshots;
    FileNode localDir;
    ArtifactRepository local;
    MavenSession session;
    RepositorySystem repoSystem;
    DefaultRepositorySystemSession repoSession;

    container = container(null, null, Logger.LEVEL_DISABLED);
    try {
        factory = container.lookup(ArtifactRepositoryFactory.class);
    } catch (ComponentLookupException e) {
        throw new IllegalStateException(e);
    }
    central = factory.createArtifactRepository("central", "http://repo1.maven.org/maven2",
            new DefaultRepositoryLayout(),
            new ArtifactRepositoryPolicy(false, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN),
            new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN));
    snapshots = factory.createArtifactRepository("apache-snapshots", "http://repository.apache.org/snapshots/",
            new DefaultRepositoryLayout(),
            new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN),
            new ArtifactRepositoryPolicy(false, ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN));
    localDir = defaultLocalRepositoryDir(world);
    local = factory.createArtifactRepository("local", localDir.getURI().toASCIIString(),
            new DefaultRepositoryLayout(),
            new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN),
            new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER,
                    ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN));

    try {
        repoSystem = container.lookup(RepositorySystem.class);
        repoSession = MavenRepositorySystemUtils.newSession();
        repoSession.setLocalRepositoryManager(
                repoSystem.newLocalRepositoryManager(repoSession, new LocalRepository(localDir.getAbsolute())));
        session = new MavenSession(container, repoSession, new DefaultMavenExecutionRequest(),
                new DefaultMavenExecutionResult());
        return new Maven(world, new DefaultLog(null), session, local, null, null,
                container.lookup(ProjectBuilder.class), Arrays.asList(central, snapshots));
    } catch (ComponentLookupException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.appformer.maven.integration.embedder.MavenEmbedder.java

License:Apache License

private MavenEmbedder(MavenRequest mavenRequest, ComponentProvider componentProvider)
        throws MavenEmbedderException {
    this.mavenRequest = mavenRequest;
    this.componentProvider = componentProvider;

    try {/*from w ww.  j ava 2 s.c o m*/
        this.mavenExecutionRequest = this.buildMavenExecutionRequest(mavenRequest);

        RepositorySystemSession rss = ((DefaultMaven) componentProvider.lookup(Maven.class))
                .newRepositorySession(mavenExecutionRequest);

        mavenSession = new MavenSession(componentProvider.getPlexusContainer(), rss, mavenExecutionRequest,
                new DefaultMavenExecutionResult());

        componentProvider.lookup(LegacySupport.class).setSession(mavenSession);
    } catch (MavenEmbedderException e) {
        log.error("Unable to build MavenEmbedder", e);
        throw e;
    } catch (ComponentLookupException e) {
        log.error("Unable to build MavenEmbedder", e);
        throw new MavenEmbedderException(e.getMessage(), e);
    }
}

From source file:org.commonjava.maven.ext.cli.Cli.java

License:Apache License

private void createSession(File target, File settings) {
    try {/*from   w ww . ja v  a  2  s . c  om*/
        final DefaultContainerConfiguration config = new DefaultContainerConfiguration();
        config.setClassPathScanning(PlexusConstants.SCANNING_ON);
        config.setComponentVisibility(PlexusConstants.GLOBAL_VISIBILITY);
        config.setName("PME-CLI");
        PlexusContainer container = new DefaultPlexusContainer(config);

        pomIO = container.lookup(PomIO.class);
        session = container.lookup(ManipulationSession.class);
        manipulationManager = container.lookup(ManipulationManager.class);

        final MavenExecutionRequest req = new DefaultMavenExecutionRequest()
                .setUserProperties(System.getProperties()).setUserProperties(userProps)
                .setRemoteRepositories(Collections.<ArtifactRepository>emptyList());

        ArtifactRepository ar = null;
        if (settings == null) {
            // No, this is not a typo. If current default is null, supply new local and global.
            // This function passes in settings to make it easier to test.
            this.settings = settings = new File(System.getProperty("user.home"), ".m2/settings.xml");

            ar = new MavenArtifactRepository();
            ar.setUrl("file://" + System.getProperty("user.home") + "/.m2/repository");
            req.setLocalRepository(ar);
        }

        req.setUserSettingsFile(settings);
        req.setGlobalSettingsFile(settings);

        MavenExecutionRequestPopulator executionRequestPopulator = container
                .lookup(MavenExecutionRequestPopulator.class);

        executionRequestPopulator.populateFromSettings(req, parseSettings(settings));
        executionRequestPopulator.populateDefaults(req);

        if (ar != null) {
            ar.setUrl("file://" + req.getLocalRepositoryPath());
        }

        if (userProps != null && userProps.containsKey("maven.repo.local")) {
            if (ar == null) {
                ar = new MavenArtifactRepository();
            }
            ar.setUrl("file://" + userProps.getProperty("maven.repo.local"));
            req.setLocalRepository(ar);
        }

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

        mavenSession.getRequest().setPom(target);

        session.setMavenSession(mavenSession);
    } catch (ComponentLookupException e) {
        logger.debug("Caught problem instantiating ", e);
        System.err.println("Unable to start Cli subsystem");
        System.exit(100);
    } catch (PlexusContainerException e) {
        logger.debug("Caught problem instantiating ", e);
        System.err.println("Unable to start Cli subsystem");
        System.exit(100);
    } catch (SettingsBuildingException e) {
        logger.debug("Caught problem parsing settings file ", e);
        System.err.println("Unable to parse settings.xml file");
        System.exit(100);
    } catch (MavenExecutionRequestPopulationException e) {
        logger.debug("Caught problem populating maven request from settings file ", e);
        System.err.println("Unable to create maven execution request from settings.xml file");
        System.exit(100);
    }
}