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

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

Introduction

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

Prototype

MavenExecutionRequest setGoals(List<String> goals);

Source Link

Usage

From source file:com.carrotgarden.m2e.config.LaunchDelegate.java

License:BSD License

private void launchMaven(final File pomFile, final List<String> commandList, final IProgressMonitor monitor)
        throws CoreException {

    final IMaven maven = MavenPlugin.getMaven();

    final Model mavenModel = maven.readModel(pomFile);

    final MavenProject mavenProject = new MavenProject(mavenModel);

    final Properties mavenProps = mavenProject.getProperties();

    for (final Map.Entry<?, ?> entry : mavenProps.entrySet()) {
        final String key = entry.getKey().toString();
        final String value = entry.getValue().toString();
        // ConfigPlugin.logInfo("key= " + key + " value=" + value);
    }// w w w.  j  ava 2s  . c  om

    //

    final List<String> goalList = new LinkedList<String>();
    final List<String> profileActiveList = new LinkedList<String>();
    final List<String> profileInactiveList = new LinkedList<String>();

    for (final String command : commandList) {

        if (command.startsWith("-")) {

            /** command line options */

            if (command.startsWith("--activate-profiles")) {
                ConfigPlugin.log(IStatus.ERROR, "TODO : " + command);
            } else {
                ConfigPlugin.log(IStatus.ERROR, "not supported : " + command);
            }

        } else {

            /** maven execution goals */

            goalList.add(command);

        }

    }

    //

    final MavenExecutionRequest request = maven.createExecutionRequest(monitor);

    request.setPom(pomFile);
    request.setGoals(goalList);

    // TODO
    // request.setActiveProfiles(profileActiveList);
    // request.setInactiveProfiles(profileInactiveList);

    //

    final String id = mavenProject.getId();

    ConfigPlugin.log(IStatus.INFO,
            "maven execute : " + mavenProject.getId() + " " + MojoUtil.join(commandList, ","));

    // final Job job = new Job(id) {
    // {
    // setSystem(true);
    // setPriority(BUILD);
    // }
    // @Override
    // protected IStatus run(final IProgressMonitor monitor) {
    // return null;
    // }
    // };

    final MavenExecutionResult result = maven.execute(request, monitor);

    if (result.hasExceptions()) {
        throw new CoreException(new Status(IStatus.ERROR, ConfigPlugin.ID, "maven execution failed",
                result.getExceptions().get(0)));
    }

}

From source file:com.cloudbees.eclipse.m2e.CBMavenUtils.java

License:Open Source License

public static IFile runMaven(IProject project, IProgressMonitor monitor, String[] goals)
        throws CloudBeesException {
    boolean pomExists = project.exists(new Path("/pom.xml"));
    if (!pomExists) {
        return null;
    }/*from   w  w  w  .jav  a2  s  .  c  o  m*/

    IMaven maven = MavenPlugin.getMaven();
    String version = MavenPlugin.getMavenRuntimeManager().getDefaultRuntime().getVersion();
    MavenExecutionRequest request;
    IMavenProjectFacade mpr = MavenPlugin.getMavenProjectRegistry().getProject(project);
    try {
        if (mpr == null) {
            // maven not configured for the project. But as pom.xml existed, let's configure.
            NatureUtil.addNatures(project, new String[] { CloudBeesNature.NATURE_ID, JavaCore.NATURE_ID,
                    "org.eclipse.m2e.core.maven2Nature" }, monitor);
            project.refreshLocal(IProject.DEPTH_INFINITE, monitor);
            mpr = MavenPlugin.getMavenProjectRegistry().getProject(project);
        }
        request = maven.createExecutionRequest(monitor);
    } catch (CoreException e) {
        throw new CloudBeesException("Failed to prepare maven war preparation request", e);
    }

    //IMavenProjectFacade facade = projectManager.create(pomFile, true, new SubProgressMonitor(monitor, 1));
    //ResolverConfiguration config = mpr.getResolverConfiguration();

    request.setPom(project.getFile(new Path("/pom.xml")).getRawLocation().toFile());
    //request.setBaseDirectory(project.getRawLocation().toFile());

    request.getSystemProperties().put("maven.test.skip", "true");

    //MavenExecutionRequest request = projectManager.createExecutionRequest(pomFile, config, new SubProgressMonitor(monitor, 1));

    //request.getUserProperties().setProperty("m2e.version", MavenPlugin.getVersion());

    //goals.add("package");
    //goals.add("eclipse:eclipse");
    request.setGoals(Arrays.asList(goals));

    //MavenPlugin.getConsole().showConsole();

    MavenExecutionResult result = maven.execute(request, monitor);
    if (result.hasExceptions()) {
        // Throw CoreException
        //System.out.println("Got exceptions while running!");
        Iterator<Throwable> it = result.getExceptions().iterator();
        Throwable e = null;

        while (it.hasNext()) {
            Throwable throwable = (Throwable) it.next();
            throwable.printStackTrace();
            e = throwable;
        }
        throw new CloudBeesException("Maven build failed!", e);
    }

    BuildSummary summary = result.getBuildSummary(result.getProject());
    MavenProject proj = summary.getProject();

    Artifact artifact = proj.getArtifact();
    File f = artifact.getFile();
    //System.out.println("Artifact: " + f);
    //System.out.println("Artifact name: " + f.getName());
    if (f == null) {
        return null;
    }
    if (BeesSDK.hasSupportedExtension(f.getName())) {
        String apath = f.getAbsolutePath().substring(project.getLocation().toFile().getAbsolutePath().length());
        //System.out.println("APATH: " + apath);
        return project.getFile(apath);
    }

    return null;
}

From source file:com.github.swt_release_fetcher.Artifact.java

License:Apache License

public void runMavenDeploy(File pomFile, File jarFile, File sourcesFile) {
    Properties properties = new Properties();
    properties.put("pomFile", pomFile.getAbsolutePath());
    properties.put("file", jarFile.getAbsolutePath());
    properties.put("sources", sourcesFile.getAbsolutePath());
    properties.put("repositoryId", "googlecode");
    properties.put("url", REPOSITORY_URL);

    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setPom(pomFile);//from www . ja v a2 s  .  co  m
    request.setGoals(Arrays.asList(new String[] { "deploy:deploy-file" }));
    request.setSystemProperties(properties);

    Maven maven = EmbeddedMaven.get();
    MavenExecutionResult result = maven.execute(request);

    if (result.hasExceptions()) {
        System.out.println("Maven deploy failed!");
        System.out.println(result.getExceptions());
        throw new RuntimeException("Maven deploy failed!", result.getExceptions().get(0));
    } else {
        System.out.println("Maven deploy succeeded!");
    }
}

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  www  . j ava 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.maltera.technologic.maven.mcforge.InstallMojo.java

License:Open Source License

public void execute() throws MojoExecutionException, MojoFailureException {
    // set up derived paths
    forgeDir = new File(outputDir, "forge");
    jarsDir = new File(forgeDir, "mcp/jars");

    // check whether the artifact is already installed 
    if (reinstall) {
        getLog().info("reinstall flag set; skipping availability check");
    } else {//from w  ww.  j  a  va2 s  .c  o  m
        getLog().info("attempting to resolve Forge artifacts");

        if (null != resolveApiArtifact() && null != resolveToolsArtifact()) {
            getLog().info("artifacts are available; skipping installation");
            return;
        } else {
            getLog().info("artifacts not available; continuing installation");
        }
    }

    if (!noExtract)
        downloadAndExtract();

    if (!forgeDir.isDirectory())
        throw new MojoFailureException("distribution did not extract to the excpected directory");

    // run the install script
    if (!noInstall) {
        getLog().info("running install script");
        try {
            final PythonLauncher launcher = new PythonLauncher(getLog(), forgeDir);

            final int result = launcher.execute(new File(forgeDir, "install.py"));

            if (0 != result) {
                throw new MojoFailureException("install script returned " + result);
            }
        } catch (IOException caught) {
            throw new MojoFailureException("error calling install script", caught);
        }
    }

    // load Minecraft's POM
    final Model minecraft = loadModelFromResouce("minecraft.pom");
    minecraft.setVersion(getMinecraftVersion());

    // figure out Minecraft's dependencies
    {
        getLog().info("detecting Minecraft dependencies");
        final Artifact lwjgl = locator.findVersion(new File(jarsDir, "bin/lwjgl.jar"), "org.lwjgl.lwjgl",
                "lwjgl");

        final Artifact lwjgl_util = new DefaultArtifact("org.lwjgl.lwjgl", "lwjgl_util", "jar",
                lwjgl.getVersion());

        // don't include jinput.jar
        // it's a transitive dependency from LWJGL

        getLog().info("resolving Minecraft dependencies");
        for (Artifact target : new Artifact[] { lwjgl, lwjgl_util }) {
            getLog().info("    " + target);

            final Artifact resolved = resolveRemoteArtifact(target);
            if (null == resolved)
                throw new MojoFailureException("unable to resolve artifact " + target);

            minecraft.addDependency(artifactToDependency(resolved));
        }
    }

    // install Minecraft JAR
    installJar(minecraft, new File(jarsDir, "bin/minecraft.jar"));

    // figure out Forge's dependencies
    // using a Map of coordinates => artifact for deduplication
    // can't use a Set, Artifact#equals() doesn't behave 
    final Map<String, Dependency> forgeDeps = new HashMap<String, Dependency>();
    for (File file : (new File(forgeDir, "mcp/lib")).listFiles()) {
        final Artifact artifact = locator.locate(file);
        if (null == artifact)
            throw new MojoFailureException("no artifact found for dependency " + file.getName());

        forgeDeps.put(artifact.toString(), artifactToDependency(artifact));
    }

    // add Minecraft client to Forge dependencies
    {
        final Artifact artifact = new DefaultArtifact("net.minecraft", "minecraft", "jar",
                getMinecraftVersion());
        forgeDeps.put(artifact.toString(), artifactToDependency(artifact));
    }

    // extract the Forge POM
    final File pom = new File(forgeDir, "pom.xml");
    {
        final Model model = loadModelFromResouce("mcforge.pom");
        model.setVersion(getApiDependency().getVersion());
        model.setDependencies(new ArrayList<Dependency>(forgeDeps.values()));
        writeModelToFile(model, pom);
    }

    // execute a build from the Forge POM
    getLog().info("executing POM to package and install artifacts");
    try {
        final MavenExecutionRequest request = new DefaultMavenExecutionRequest();
        requestPopulator.populateDefaults(request);

        request.setPom(pom);
        request.setGoals(Collections.singletonList("install"));

        final MavenExecutionResult result = maven.execute(request);

        // check for startup exceptions
        if (result.hasExceptions())
            throw new MojoFailureException("failed to package and install artifacts",
                    result.getExceptions().get(0));

        // check for build failure
        final BuildSummary summary = result.getBuildSummary(result.getProject());
        if (summary instanceof BuildFailure) {
            throw new MojoFailureException("failed to package and install artifacts",
                    ((BuildFailure) summary).getCause());
        }
    } catch (MojoFailureException caught) {
        throw caught;
    } catch (Exception caught) {
        throw new MojoFailureException("failed to package and install artifacts", caught);
    }
}

From source file:ead.exporter.ApkExporter.java

License:Open Source License

@Override
public void export(String gameBaseDir, String outputfolder) {

    if (packageName == null) {
        logger.error("app name is not set or is invalid. Apk exportation failed.");
        return;/*from  ww  w .java  2  s.  c  om*/
    }

    // Create a temp folder to generate de apk
    File gameFolder = new File(gameBaseDir);
    String tempFolder = System.getProperty("java.io.tmpdir");
    File apkTemp = new File(
            tempFolder + File.separator + "eAdventureApkTemp" + Math.round(Math.random() * 1000));
    apkTemp.mkdirs();

    File manifestFile = createManifest(apkTemp);
    File apkAssets = createAssetsFolder(apkTemp, gameFolder);
    File apkResources = createResourcesFolder(apkTemp);

    // Copy native libs folder
    try {
        FileUtils.copyDirectoryStructure(new File("../../resources/nativelibs"), apkTemp);
    } catch (IOException e) {

    }

    // Copy and load pom file
    File pomFile = createPomFile(apkTemp);
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();

    // Goals
    File f = new File(apkTemp, "/target/classes");
    f.mkdirs();
    ArrayList<String> goals = new ArrayList<String>();
    goals.add("clean");
    goals.add("install");
    if (runInDevice) {
        goals.add("android:deploy");
        goals.add("android:run");
    }
    request.setGoals(goals);

    // Properties
    Properties userProperties = new Properties();
    userProperties.setProperty("game.basedir", gameBaseDir);
    userProperties.setProperty("game.outputfolder", outputfolder);
    userProperties.setProperty("game.name", appName);
    userProperties.setProperty("ead.packagename", packageName);
    userProperties.setProperty("eadmanifestdir", manifestFile.getAbsolutePath());
    userProperties.setProperty("ead.tempfile", apkTemp.getAbsolutePath());
    userProperties.setProperty("ead.assets", apkAssets.getAbsolutePath());
    userProperties.setProperty("ead.resources", apkResources.getAbsolutePath());

    request.setUserProperties(userProperties);

    // Set files
    request.setBaseDirectory(apkTemp);
    request.setPom(pomFile);

    // Execute maven
    request.setLoggingLevel(org.codehaus.plexus.logging.Logger.LEVEL_ERROR);

    MavenExecutionResult result = maven.execute(request);
    for (Throwable e : result.getExceptions()) {
        logger.warn("{}", e);
    }

    // Copy apk to destination
    File apk = new File(apkTemp, "target/" + packageName + ".apk");
    File apkDst = new File(outputfolder, packageName + ".apk");

    try {
        FileUtils.copyFile(apk, apkDst);
    } catch (IOException e1) {

    }

    // Delete temp folder
    try {
        FileUtils.deleteDirectory(apkTemp);
    } catch (IOException e) {
        logger.warn("Apk assets temp folder was not deleted {}", e);
    }

}

From source file:ead.exporter.JarExporter.java

License:Open Source License

public void export(String gameBaseDir, String outputfolder) {
    String tempFolder = System.getProperty("java.io.tmpdir");
    File jarTemp = new File(
            tempFolder + File.separator + "eAdventureJarTemp" + Math.round(Math.random() * 1000));
    jarTemp.mkdirs();// ww  w .j  av  a  2s  .c om

    // Load pom file
    File pomFile = new File(jarTemp, "pom.xml");
    try {
        FileUtils.copyStreamToFile(
                new RawInputStreamFacade(ClassLoader.getSystemResourceAsStream("pom/desktoppom.xml")), pomFile);
    } catch (IOException e1) {

    }

    MavenExecutionRequest request = new DefaultMavenExecutionRequest();

    // Goals
    ArrayList<String> goals = new ArrayList<String>();
    goals.add("package");
    request.setGoals(goals);

    // Properties
    Properties userProperties = new Properties();
    userProperties.setProperty("game.basedir", gameBaseDir);
    userProperties.setProperty("game.outputfolder", outputfolder);
    userProperties.setProperty("game.name", name);
    request.setUserProperties(userProperties);

    // Set files
    request.setBaseDirectory(jarTemp);
    request.setPom(pomFile);

    // Execute maven
    MavenExecutionResult result = maven.execute(request);
    for (Throwable e : result.getExceptions()) {
        e.printStackTrace();
    }

    // Copy to output folder
    File jarFile = new File(jarTemp, "target/desktop-game-1.0-unified.jar");
    File dstFile = new File(outputfolder, name + ".jar");
    try {
        FileUtils.copyFile(jarFile, dstFile);
    } catch (IOException e2) {

    }

    try {
        FileUtils.deleteDirectory(jarTemp);
    } catch (IOException e1) {

    }

}

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 w w  . jav a 2s .  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.che.maven.server.MavenServerImpl.java

License:Open Source License

public MavenExecutionRequest newMavenRequest(File pom, List<String> activeProfiles,
        List<String> inactiveProfiles, List<String> goals) {
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    try {//  www .  j a  v a  2  s  . c  om
        getMavenComponent(MavenExecutionRequestPopulator.class).populateFromSettings(request, settings);
        request.setGoals(goals);
        request.setPom(pom);
        getMavenComponent(MavenExecutionRequestPopulator.class).populateDefaults(request);
        request.setSystemProperties(properties);
        request.setActiveProfiles(activeProfiles);
        request.setInactiveProfiles(inactiveProfiles);
        request.setStartTime(buildDate);
        return request;

    } catch (MavenExecutionRequestPopulationException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.m2e.core.ui.internal.wizards.MavenInstallFileWizard.java

License:Open Source License

public boolean performFinish() {
    final Properties properties = new Properties();

    // Mandatory Properties for install:install-file
    properties.setProperty("file", artifactPage.getArtifactFileName()); //$NON-NLS-1$

    properties.setProperty("groupId", artifactPage.getGroupId()); //$NON-NLS-1$
    properties.setProperty("artifactId", artifactPage.getArtifactId()); //$NON-NLS-1$
    properties.setProperty("version", artifactPage.getVersion()); //$NON-NLS-1$
    properties.setProperty("packaging", artifactPage.getPackaging()); //$NON-NLS-1$

    if (artifactPage.getClassifier().length() > 0) {
        properties.setProperty("classifier", artifactPage.getClassifier()); //$NON-NLS-1$
    }//from  w  w w.  j  ava 2s  .  co  m

    if (artifactPage.getPomFileName().length() > 0) {
        properties.setProperty("pomFile", artifactPage.getPomFileName()); //$NON-NLS-1$
    }
    if (artifactPage.isGeneratePom()) {
        properties.setProperty("generatePom", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (artifactPage.isCreateChecksum()) {
        properties.setProperty("createChecksum", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    new Job(Messages.MavenInstallFileWizard_job) {
        protected IStatus run(IProgressMonitor monitor) {
            setProperty(IProgressConstants.ACTION_PROPERTY, new OpenMavenConsoleAction());
            try {
                // Run the install:install-file goal
                IMaven maven = MavenPlugin.getMaven();
                MavenExecutionRequest request = maven.createExecutionRequest(monitor);
                request.setGoals(Arrays.asList("install:install-file")); //$NON-NLS-1$
                request.setUserProperties(properties);
                MavenExecutionResult executionResult = maven.execute(request, monitor);

                List<Throwable> exceptions = executionResult.getExceptions();
                if (!exceptions.isEmpty()) {
                    for (Throwable exception : exceptions) {
                        String msg = Messages.MavenInstallFileWizard_error;
                        msg += "; " + exception.toString(); //$NON-NLS-1$
                        log.error(msg, exception);
                    }
                }

                // TODO update index for local maven repository
            } catch (CoreException ex) {
                log.error("Failed to install artifact:" + ex.getMessage(), ex);
            }
            return Status.OK_STATUS;
        }
    }.schedule();

    return true;
}