Example usage for org.apache.maven.execution DefaultMavenExecutionRequest copy

List of usage examples for org.apache.maven.execution DefaultMavenExecutionRequest copy

Introduction

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

Prototype

public static MavenExecutionRequest copy(MavenExecutionRequest original) 

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 ww  w .ja va2s.  c om
        //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: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).//  w w  w .j a v a 2  s  .c  o m
 */
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.eclipse.m2e.core.internal.embedder.MavenExecutionContext.java

License:Open Source License

protected MavenExecutionRequest newExecutionRequest() throws CoreException {
    MavenExecutionRequest request = null;
    Deque<MavenExecutionContext> stack = context.get();
    if (stack != null && !stack.isEmpty()) {
        MavenExecutionRequest parent = stack.peek().request;
        if (parent == null) {
            throw new IllegalStateException(); // 
        }//from  www.  j  a v  a  2  s. com
        request = DefaultMavenExecutionRequest.copy(parent);
    }
    if (request == null) {
        request = maven.createExecutionRequest();
    }
    return request;
}

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

License:Open Source License

public MavenProject readProject(final File pomFile, IProgressMonitor monitor) throws CoreException {
    return context().execute(new ICallable<MavenProject>() {
        public MavenProject call(IMavenExecutionContext context, IProgressMonitor monitor)
                throws CoreException {
            MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(context.getExecutionRequest());
            try {
                lookup(MavenExecutionRequestPopulator.class).populateDefaults(request);
                ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
                configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
                configuration.setRepositorySession(createRepositorySession(request));
                return lookup(ProjectBuilder.class).build(pomFile, configuration).getProject();
            } catch (ProjectBuildingException ex) {
                throw new CoreException(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1,
                        Messages.MavenImpl_error_read_project, ex));
            } catch (MavenExecutionRequestPopulationException ex) {
                throw new CoreException(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1,
                        Messages.MavenImpl_error_read_project, ex));
            }//  w  w  w. ja v a2 s .c o m
        }
    }, monitor);
}

From source file:org.jooby.JoobyMojo.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from w  w  w .  jav a 2s. c om*/
public void execute() throws MojoExecutionException, MojoFailureException {

    Set<File> appcp = new LinkedHashSet<>();

    // public / config, etc..
    appcp.addAll(resources(mavenProject.getResources()));

    // target/classes
    appcp.add(new File(buildOutputDirectory));

    // references project
    Set<Artifact> references = references(mavenProject);
    Set<File> refbasedir = refbasedir(mavenProject, references);
    Set<File> refcp = refcp(refbasedir);
    appcp.addAll(refcp);

    // *.jar
    Set<Artifact> artifacts = new LinkedHashSet<Artifact>(mavenProject.getArtifacts());

    artifacts.forEach(artifact -> {
        if (!"pom".equals(artifact.getType())) {
            // ignore self reference
            appcp.add(new File(artifact.getFile().getAbsolutePath()));
        }
    });

    Set<File> classpath = new LinkedHashSet<>();

    File hotreload = extra(pluginArtifacts, "jooby-run").get();
    File jbossModules = extra(pluginArtifacts, "jboss-modules").get();
    classpath.add(hotreload);
    classpath.add(jbossModules);

    // prepare commands
    List<Command> cmds = new ArrayList<>();
    if (commands != null && commands.size() > 0) {
        cmds.addAll(this.commands);
    }

    // watch dir
    List<File> watchDirs = new ArrayList<>();
    watchDirs.add(mavenProject.getBasedir());
    watchDirs.addAll(refbasedir);
    if (this.watchDirs != null) {
        this.watchDirs.forEach(f -> watchDirs.add(new File(f)));
    }

    // includes/excludes pattern
    String includes = null;
    if (this.includes != null && this.includes.size() > 0) {
        includes = this.includes.stream().collect(Collectors.joining(File.pathSeparator));
    }
    String excludes = null;
    if (this.excludes != null && this.excludes.size() > 0) {
        excludes = this.excludes.stream().collect(Collectors.joining(File.pathSeparator));
    }
    String watchDirStr = watchDirs.stream().filter(File::exists).map(File::getAbsolutePath)
            .collect(Collectors.joining(File.pathSeparator));
    // moduleId
    String mId = mavenProject.getGroupId() + "." + mavenProject.getArtifactId();

    // logback and application.version
    setLogback();
    System.setProperty("application.version", mavenProject.getVersion());

    // fork?
    Command runapp = fork
            ? new RunForkedApp(mavenProject.getBasedir(), debug, vmArgs, classpath, mId, mainClass, appcp,
                    includes, excludes, watchDirStr)
            : new RunApp(mId, mainClass, appcp, includes, excludes, watchDirs);

    // run app at the end
    cmds.add(runapp);

    for (Command cmd : cmds) {
        cmd.setWorkdir(mavenProject.getBasedir());
        getLog().debug("cmd: " + cmd.debug());
    }

    Watcher watcher = setupCompiler(mavenProject, compiler, goal -> {
        maven.execute(DefaultMavenExecutionRequest.copy(session.getRequest()).setGoals(Arrays.asList(goal)));
    });

    ShutdownHook shutdownHook = new ShutdownHook(getLog(), cmds);
    shutdownHook.watcher = watcher;
    /**
     * Shutdown hook
     */
    Runtime.getRuntime().addShutdownHook(shutdownHook);

    if (watcher != null) {
        watcher.start();
    }

    /**
     * Start process
     */
    for (Command cmd : cmds) {
        try {
            getLog().debug("Starting process: " + cmd.debug());
            cmd.execute();
        } catch (Exception ex) {
            throw new MojoFailureException("Execution of " + cmd + " resulted in error", ex);
        }
    }

}

From source file:org.kie.workbench.common.services.backend.compiler.external339.AFMavenCli.java

License:Apache License

protected List<CoreExtensionEntry> loadCoreExtensions(AFCliRequest cliRequest, ClassRealm containerRealm,
        Set<String> providedArtifacts) {
    if (cliRequest.getMultiModuleProjectDirectory() == null) {
        return Collections.emptyList();
    }//w w  w.j ava  2 s.  c  o m

    Path extensionsFile = Paths.get(cliRequest.getMultiModuleProjectDirectory().toString(),
            EXTENSIONS_FILENAME);
    if (!java.nio.file.Files.isRegularFile(extensionsFile)) {
        return Collections.emptyList();
    }

    try {
        List<CoreExtension> extensions = readCoreExtensionsDescriptor(extensionsFile);
        if (extensions.isEmpty()) {
            return Collections.emptyList();
        }

        ContainerConfiguration cc = new DefaultContainerConfiguration() //
                .setClassWorld(cliRequest.getClassWorld()) //
                .setRealm(containerRealm) //
                .setClassPathScanning(PlexusConstants.SCANNING_INDEX) //
                .setAutoWiring(true) //
                .setName("maven");

        DefaultPlexusContainer container = new DefaultPlexusContainer(cc, new AbstractModule() {
            @Override
            protected void configure() {
                bind(ILoggerFactory.class).toInstance(slf4jLoggerFactory);
            }
        });

        try {
            container.setLookupRealm(null);

            container.setLoggerManager(plexusLoggerManager);

            container.getLoggerManager().setThresholds(cliRequest.getRequest().getLoggingLevel());

            Thread.currentThread().setContextClassLoader(container.getContainerRealm());

            executionRequestPopulator = container.lookup(MavenExecutionRequestPopulator.class);

            configurationProcessors = container.lookupMap(AFConfigurationProcessor.class);

            configure(cliRequest);

            MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(cliRequest.getRequest());

            request = populateRequest(cliRequest, request);

            request = executionRequestPopulator.populateDefaults(request);

            BootstrapCoreExtensionManager resolver = container.lookup(BootstrapCoreExtensionManager.class);

            return resolver.loadCoreExtensions(request, providedArtifacts, extensions);
        } finally {
            executionRequestPopulator = null;
            container.dispose();
        }
    } catch (RuntimeException e) {
        // runtime exceptions are most likely bugs in maven, let them bubble up to the user
        throw e;
    } catch (Exception e) {
        slf4jLogger.warn("Failed to read extensions descriptor " + extensionsFile + ": " + e.getMessage());
    }
    return Collections.emptyList();
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.ReusableAFMavenCli.java

License:Apache License

protected List<CoreExtensionEntry> loadCoreExtensions(AFCliRequest cliRequest, ClassRealm containerRealm,
        Set<String> providedArtifacts) {
    if (cliRequest.getMultiModuleProjectDirectory() == null) {
        return Collections.emptyList();
    }//from   w ww. j  a va 2s  .  c om

    Path extensionsFile = Paths.get(cliRequest.getMultiModuleProjectDirectory().toString(),
            EXTENSIONS_FILENAME);
    if (!java.nio.file.Files.isRegularFile(extensionsFile)) {
        return Collections.emptyList();
    }

    try {
        List<CoreExtension> extensions = readCoreExtensionsDescriptor(extensionsFile);
        if (extensions.isEmpty()) {
            return Collections.emptyList();
        }

        ContainerConfiguration cc = new DefaultContainerConfiguration() //
                .setClassWorld(cliRequest.getClassWorld()) //
                .setRealm(containerRealm) //
                .setClassPathScanning(PlexusConstants.SCANNING_INDEX) //
                .setAutoWiring(true) //
                .setName("maven");
        if (reusableContainerCoreExtensions == null) {
            reusableContainerCoreExtensions = new DefaultPlexusContainer(cc, new AbstractModule() {
                @Override
                protected void configure() {
                    bind(ILoggerFactory.class).toInstance(slf4jLoggerFactory);
                }
            });
        }

        try {
            reusableContainerCoreExtensions.setLookupRealm(null);

            ((DefaultPlexusContainer) reusableContainerCoreExtensions).setLoggerManager(plexusLoggerManager);

            ((DefaultPlexusContainer) reusableContainerCoreExtensions).getLoggerManager()
                    .setThresholds(cliRequest.getRequest().getLoggingLevel());

            Thread.currentThread().setContextClassLoader(reusableContainerCoreExtensions.getContainerRealm());

            reusableExecutionRequestPopulator = reusableContainerCoreExtensions
                    .lookup(MavenExecutionRequestPopulator.class);

            reusableConfigurationProcessors = reusableContainerCoreExtensions
                    .lookupMap(AFConfigurationProcessor.class);

            configure(cliRequest);

            MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(cliRequest.getRequest());

            request = populateRequest(cliRequest, request);

            request = reusableExecutionRequestPopulator.populateDefaults(request);

            BootstrapCoreExtensionManager resolver = reusableContainerCoreExtensions
                    .lookup(BootstrapCoreExtensionManager.class);

            reusableExtensions = resolver.loadCoreExtensions(request, providedArtifacts, extensions);

            return reusableExtensions;
        } finally {
            reusableExecutionRequestPopulator = null;
        }
    } catch (RuntimeException e) {
        // runtime exceptions are most likely bugs in maven, let them bubble up to the user
        throw e;
    } catch (Exception e) {
        reusableSlf4jLogger
                .warn("Failed to read extensions descriptor " + extensionsFile + ": " + e.getMessage());
    }
    return Collections.emptyList();
}

From source file:org.openengsb.openengsbplugin.tools.DefaultMavenExecutor.java

License:Apache License

private MavenExecutionRequest generateRequestFromWrapperRequest(MavenSession session) {
    MavenExecutionRequest wrapperRequest = session.getRequest();
    return DefaultMavenExecutionRequest.copy(wrapperRequest);
}

From source file:org.sourcepit.maven.bootstrap.core.AbstractBootstrapper.java

License:Apache License

private MavenSession createBootSession(MavenSession actualSession) {
    final DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(
            actualSession.getRepositorySession());
    final DefaultMavenExecutionRequest executionRequest = (DefaultMavenExecutionRequest) DefaultMavenExecutionRequest
            .copy(actualSession.getRequest());
    // fix: copy ignores start time...
    executionRequest.setStartTime(actualSession.getRequest().getStartTime());
    // fix: copy ignores project building request...
    executionRequest.setProjectBuildingConfiguration(
            new DefaultProjectBuildingRequest(actualSession.getRequest().getProjectBuildingRequest()));
    final DefaultMavenExecutionResult executionResult = new DefaultMavenExecutionResult();
    return new MavenSession(plexusContainer, repositorySession, executionRequest, executionResult);
}

From source file:org.wisdom.maven.mojos.RunMojo.java

License:Apache License

private MavenExecutionRequest getMavenExecutionRequest() {
    MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest());
    request.setStartTime(session.getStartTime());
    request.setExecutionListener(null);/* ww w. j av  a  2  s  .  co  m*/
    if (!initialBuild && session.getGoals().contains("clean")) {
        // Here the package phase is required to restore the runtime environment
        request.setGoals(ImmutableList.of("clean", "package", "wisdom:internal-run"));
    } else {
        // It is safer to re-execute the package phase to have the new classes...
        request.setGoals(ImmutableList.of("package", "wisdom:internal-run"));
    }
    return request;
}