Example usage for org.apache.maven.execution MavenExecutionRequest setExecutionListener

List of usage examples for org.apache.maven.execution MavenExecutionRequest setExecutionListener

Introduction

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

Prototype

MavenExecutionRequest setExecutionListener(ExecutionListener executionListener);

Source Link

Usage

From source file:com.github.htfv.maven.plugins.buildconfigurator.core.configurators.propertyfiles.PropertyFileConfigurator.java

License:Apache License

/**
 * Reinterpolates all elements of the project model.
 *
 * @param ctx//  w w  w . j av  a  2 s. co m
 *            The configuration context.
 * @param resultBuilder
 *            The result builder.
 */
private void reinterpolateProjectModel(final ConfigurationContext ctx, final Result.Builder resultBuilder) {
    //
    // Maven interpolates expressions when it loads the model. Since the
    // properties are loaded after the model, we have to interpolate
    // expressions again.
    //
    // It is actually not required for mojo parameters, because parameters
    // are interpolated before mojo is executed. However, it can be a
    // problem if mojo accesses model, like maven-resources-plugin accessing
    // project.build.resources.
    //
    // We take a conservative approach and only replace properties which
    // were loaded by the build configurator.
    //

    final ModelInterpolator interpolator = new ModelInterpolator(resultBuilder.newProperties());

    interpolator.interpolateModel(ctx.getProject().getModel());

    //
    // Maven interpolates mojo parameters before execution, but it skips
    // parameters of the PlexusConfiguration type. Updating the model now
    // has no effect, because execution plan is already calculated and mojo
    // configuration is copied to mojo execution. We cannot get access to
    // mojo execution, so we register a listener which will be called before
    // mojo is executed.
    //

    if (!ctx.getRequest().isConnectorRequest()) {
        final MavenSession mavenSession = ctx.getMavenSession();
        final MavenExecutionRequest executionRequest = mavenSession.getRequest();
        final ExecutionListener executionListener = executionRequest.getExecutionListener();

        executionRequest.setExecutionListener(new DelegatingExecutionListener(executionListener) {
            @Override
            public void mojoStarted(final ExecutionEvent event) {
                interpolator.interpolateDOM(event.getMojoExecution().getConfiguration());

                super.mojoStarted(event);
            }

            @Override
            public void projectFailed(final ExecutionEvent event) {
                event.getSession().getRequest().setExecutionListener(getDelegate());
                super.projectFailed(event);
            }

            @Override
            public void projectSucceeded(final ExecutionEvent event) {
                event.getSession().getRequest().setExecutionListener(getDelegate());
                super.projectSucceeded(event);
            }
        });
    }
}

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  ww  .  j a  va 2 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.sumologic.maven.stats.SumoLogicProfilingParticipant.java

License:Apache License

private void ensureInstalled(MavenSession session) {
    if (!installed) {
        synchronized (this) {
            if (!installed) { // Double lock makes this thread safe and does not repeat the work
                MavenExecutionRequest request = session.getRequest();
                ExecutionListener currentListener = request.getExecutionListener();

                String sumoEndpoint = session.getCurrentProject().getProperties()
                        .getProperty("sumologic.http.endpoint");
                ProfilingSerializer serializer = new JsonProfilingSerializer();
                ProfilingPublisher profilingPublisher = new SumoLogicProfilingPublisher(logger, sumoEndpoint,
                        serializer);/* ww w .  j  a va 2  s .  c  o  m*/
                ExecutionListener profilingListener = new ProfilePublishingExecutionListener(
                        profilingPublisher);

                ExecutionListener chainedListener = ChainedExecutionListener.buildFrom(currentListener,
                        profilingListener);
                request.setExecutionListener(chainedListener);

                installed = true;
            }
        }
    }
}

From source file:hudson.maven.MavenEmbedder.java

License:Apache License

protected MavenExecutionRequest buildMavenExecutionRequest(MavenRequest mavenRequest)
        throws MavenEmbedderException, ComponentLookupException {
    MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();

    if (mavenRequest.getGlobalSettingsFile() != null) {
        mavenExecutionRequest.setGlobalSettingsFile(new File(mavenRequest.getGlobalSettingsFile()));
    }//from w w  w  .ja v  a2 s  .  c o  m

    if (mavenExecutionRequest.getUserSettingsFile() != null) {
        mavenExecutionRequest.setUserSettingsFile(new File(mavenRequest.getUserSettingsFile()));
    }

    try {
        lookup(MavenExecutionRequestPopulator.class).populateFromSettings(mavenExecutionRequest, getSettings());

        lookup(MavenExecutionRequestPopulator.class).populateDefaults(mavenExecutionRequest);
    } catch (MavenExecutionRequestPopulationException e) {
        throw new MavenEmbedderException(e.getMessage(), e);
    }

    ArtifactRepository localRepository = getLocalRepository();
    mavenExecutionRequest.setLocalRepository(localRepository);
    mavenExecutionRequest.setLocalRepositoryPath(localRepository.getBasedir());
    mavenExecutionRequest.setOffline(mavenRequest.isOffline());

    mavenExecutionRequest.setUpdateSnapshots(mavenRequest.isUpdateSnapshots());

    // TODO check null and create a console one ?
    mavenExecutionRequest.setTransferListener(mavenRequest.getTransferListener());

    mavenExecutionRequest.setCacheNotFound(mavenRequest.isCacheNotFound());
    mavenExecutionRequest.setCacheTransferError(true);

    mavenExecutionRequest.setUserProperties(mavenRequest.getUserProperties());
    mavenExecutionRequest.getSystemProperties().putAll(System.getProperties());
    if (mavenRequest.getSystemProperties() != null) {
        mavenExecutionRequest.getSystemProperties().putAll(mavenRequest.getSystemProperties());
    }
    mavenExecutionRequest.getSystemProperties().putAll(getEnvVars());

    if (this.mavenHome != null) {
        mavenExecutionRequest.getSystemProperties().put("maven.home", this.mavenHome.getAbsolutePath());
    }

    if (mavenRequest.getProfiles() != null && !mavenRequest.getProfiles().isEmpty()) {
        for (String id : mavenRequest.getProfiles()) {
            Profile p = new Profile();
            p.setId(id);
            p.setSource("cli");
            mavenExecutionRequest.addProfile(p);
            mavenExecutionRequest.addActiveProfile(id);
        }
    }

    mavenExecutionRequest.setLoggingLevel(mavenRequest.getLoggingLevel());

    lookup(Logger.class).setThreshold(mavenRequest.getLoggingLevel());

    mavenExecutionRequest.setExecutionListener(mavenRequest.getExecutionListener())
            .setInteractiveMode(mavenRequest.isInteractive())
            .setGlobalChecksumPolicy(mavenRequest.getGlobalChecksumPolicy()).setGoals(mavenRequest.getGoals());

    if (mavenRequest.getPom() != null) {
        mavenExecutionRequest.setPom(new File(mavenRequest.getPom()));
    }

    if (mavenRequest.getWorkspaceReader() != null) {
        mavenExecutionRequest.setWorkspaceReader(mavenRequest.getWorkspaceReader());
    }

    // FIXME inactive profiles 

    //this.mavenExecutionRequest.set

    return mavenExecutionRequest;

}

From source file:io.fabric8.vertx.maven.plugin.mojos.MojoSpy.java

License:Apache License

public static void init(MavenExecutionRequest request) {
    request.setExecutionListener(new MojoSpy(request));
}

From source file:io.takari.maven.timeline.BuildEventsExtension.java

License:Apache License

@Override
public void afterProjectsRead(MavenSession session) {
    MavenExecutionRequest request = session.getRequest();
    ExecutionListener original = request.getExecutionListener();
    BuildEventListener listener = new BuildEventListener(logFile(session), mavenTimelineFile(session));
    ExecutionListener chain = new ExecutionListenerChain(original, listener);
    request.setExecutionListener(chain);
}

From source file:net.gageot.maven.BuildEventsExtension.java

License:Apache License

@Override
public void afterProjectsRead(MavenSession session) {
    MavenExecutionRequest request = session.getRequest();

    ExecutionListener original = request.getExecutionListener();
    BuildEventListener listener = new BuildEventListener(logFile(session));
    ExecutionListener chain = new ExecutionListenerChain(original, listener);

    request.setExecutionListener(chain);
}

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

License:Apache License

/**
 * Creates the MAVEN session.//from  ww  w  .  java 2 s  . c  o  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.Maven.java

License:Apache License

/**
 * Creates an DefaultMaven instance, initializes it form parentRequest (in Maven, this is done by MavenCli - also by
 * loading settings).//from  w  ww . jav a  2s  .com
 */
public void build(FileNode basedir, Map<String, String> userProperties, ExecutionListener theExecutionListener,
        FilteringMojoExecutor.Filter filter, String... goals) throws BuildException {
    DefaultPlexusContainer container;
    org.apache.maven.Maven maven;
    MavenExecutionRequest request;
    MavenExecutionResult result;
    BuildException exception;
    FilteringMojoExecutor mojoExecutor;

    request = DefaultMavenExecutionRequest.copy(parentSession.getRequest());
    container = (DefaultPlexusContainer) parentSession.getContainer();
    try {
        maven = container.lookup(org.apache.maven.Maven.class);
    } catch (ComponentLookupException e) {
        throw new IllegalStateException(e);
    }
    request.setPom(basedir.join("pom.xml").toPath().toFile());
    request.setProjectPresent(true);
    request.setGoals(Arrays.asList(goals));
    request.setBaseDirectory(basedir.toPath().toFile());
    request.setUserProperties(merged(request.getUserProperties(), userProperties));
    request.setExecutionListener(theExecutionListener);

    mojoExecutor = FilteringMojoExecutor.install(container, filter);
    log.info("[" + basedir + " " + filter + "] mvn " + props(request.getUserProperties())
            + Separator.SPACE.join(goals));
    nestedOutputOn();
    try {
        result = maven.execute(request);
    } finally {
        nestedOutputOff();
        mojoExecutor.uninstall();
    }
    exception = null;
    for (Throwable e : result.getExceptions()) {
        if (exception == null) {
            exception = new BuildException("build failed: " + e, e);
        } else {
            exception.addSuppressed(e);
        }
    }
    if (exception != null) {
        throw exception;
    }
}

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

License:Apache License

protected MavenExecutionRequest buildMavenExecutionRequest(MavenRequest mavenRequest)
        throws MavenEmbedderException, ComponentLookupException {
    MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();

    if (mavenRequest.getGlobalSettingsFile() != null) {
        mavenExecutionRequest.setGlobalSettingsFile(new File(mavenRequest.getGlobalSettingsFile()));
    }/*from  w  w w  .  j  a  v  a 2s  .c o  m*/

    SettingsSource userSettings = mavenRequest.getUserSettingsSource();
    if (userSettings != null) {
        if (userSettings instanceof FileSettingsSource) {
            mavenExecutionRequest.setUserSettingsFile(((FileSettingsSource) userSettings).getSettingsFile());
        } else {
            try {
                mavenExecutionRequest.setUserSettingsFile(copyInTempFile(userSettings.getInputStream(), "xml"));
            } catch (IOException ioe) {
                log.warn("Unable to use maven settings defined in " + userSettings, ioe);
            }
        }
    }

    try {
        componentProvider.lookup(MavenExecutionRequestPopulator.class)
                .populateFromSettings(mavenExecutionRequest, getSettings());
        componentProvider.lookup(MavenExecutionRequestPopulator.class).populateDefaults(mavenExecutionRequest);
    } catch (MavenExecutionRequestPopulationException e) {
        throw new MavenEmbedderException(e.getMessage(), e);
    }

    ArtifactRepository localRepository = getLocalRepository();
    mavenExecutionRequest.setLocalRepository(localRepository);
    mavenExecutionRequest.setLocalRepositoryPath(localRepository.getBasedir());
    mavenExecutionRequest.setOffline(mavenRequest.isOffline());

    mavenExecutionRequest.setUpdateSnapshots(mavenRequest.isUpdateSnapshots());

    // TODO check null and create a console one ?
    mavenExecutionRequest.setTransferListener(mavenRequest.getTransferListener());

    mavenExecutionRequest.setCacheNotFound(mavenRequest.isCacheNotFound());
    mavenExecutionRequest.setCacheTransferError(true);

    mavenExecutionRequest.setUserProperties(mavenRequest.getUserProperties());
    mavenExecutionRequest.getSystemProperties().putAll(System.getProperties());
    if (mavenRequest.getSystemProperties() != null) {
        mavenExecutionRequest.getSystemProperties().putAll(mavenRequest.getSystemProperties());
    }
    mavenExecutionRequest.getSystemProperties().putAll(getEnvVars());

    if (mavenRequest.getProfiles() != null && !mavenRequest.getProfiles().isEmpty()) {
        for (String id : mavenRequest.getProfiles()) {
            Profile p = new Profile();
            p.setId(id);
            p.setSource("cli");
            mavenExecutionRequest.addProfile(p);
            mavenExecutionRequest.addActiveProfile(id);
        }
    }

    MavenRepositoryConfiguration mavenRepoConf = getMavenRepositoryConfiguration();

    //DROOLS-899: Copy repositories defined in settings to execution request
    for (ArtifactRepository artifactRepository : mavenRepoConf.getArtifactRepositoriesForRequest()) {
        mavenExecutionRequest.addRemoteRepository(artifactRepository);
    }

    mavenExecutionRequest.setProxies(mavenRepoConf.getProxies());

    mavenExecutionRequest.setLoggingLevel(mavenRequest.getLoggingLevel());

    componentProvider.lookup(Logger.class).setThreshold(mavenRequest.getLoggingLevel());

    mavenExecutionRequest.setExecutionListener(mavenRequest.getExecutionListener())
            .setInteractiveMode(mavenRequest.isInteractive())
            .setGlobalChecksumPolicy(mavenRequest.getGlobalChecksumPolicy()).setGoals(mavenRequest.getGoals());

    if (mavenRequest.getPom() != null) {
        mavenExecutionRequest.setPom(new File(mavenRequest.getPom()));
    }

    if (mavenRequest.getWorkspaceReader() != null) {
        mavenExecutionRequest.setWorkspaceReader(mavenRequest.getWorkspaceReader());
    }

    return mavenExecutionRequest;
}