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

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

Introduction

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

Prototype

MavenExecutionRequest setBaseDirectory(File basedir);

Source Link

Usage

From source file:com.googlecode.ounit.executor.MavenRunner.java

License:Open Source License

public MavenExecutionResult execute(File baseDirectory, List<String> goals, String outputDirectory) {

    baseDirectory = baseDirectory.getAbsoluteFile();
    File pom = modelProcessor.locatePom(baseDirectory);

    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setBaseDirectory(baseDirectory).setPom(pom).setExecutionListener(executionListener)
            .setTransferListener(transferListener).setSystemProperties(systemProperties)
            //.setUserProperties( userProperties )
            .setLoggingLevel(logLevel).setInteractiveMode(false)
            //.setOffline( true )
            .setCacheNotFound(true).setCacheTransferError(false).setGoals(goals);

    /* Apply base profiles */
    for (Profile p : baseProfiles)
        request.addProfile(p.clone());/*from  w  w w.j a va2  s  . c om*/

    // TODO: Implement system specific settings.xml file

    /* Create a build profile to set outputDirectory */
    if (outputDirectory != null) {
        Build b = new Build();
        b.setDirectory(outputDirectory);
        Activation a = new Activation();
        a.setActiveByDefault(true);
        Profile p = new Profile();
        p.setId("ounitExecutorCustomOutputDirectoryProfile");
        p.setActivation(a);
        p.setBuild(b);
        request.addProfile(p);
    }

    container.getLoggerManager().setThresholds(request.getLoggingLevel());

    MavenExecutionResult r = maven.execute(request);

    return r;
}

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

    // 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();/*  w ww . j a va 2  s  .co  m*/

    // 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:io.takari.maven.testing.Maven30xRuntime.java

License:Open Source License

@Override
public MavenProject readMavenProject(File basedir) throws Exception {
    File pom = new File(basedir, "pom.xml");
    MavenExecutionRequest request = newExecutionRequest();
    request.setBaseDirectory(basedir);
    ProjectBuildingRequest configuration = getProjectBuildingRequest(request);
    return container.lookup(ProjectBuilder.class).build(getPomFile(pom), configuration).getProject();
}

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   ww  w .java2  s.c om
 */
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.tycho.testing.AbstractTychoMojoTestCase.java

License:Open Source License

protected MavenExecutionRequest newMavenExecutionRequest(File pom) throws Exception {
    Properties systemProps = new Properties();
    systemProps.putAll(System.getProperties());

    Properties userProps = new Properties();
    userProps.put("tycho-version", "0.0.0");

    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setBaseDirectory(pom.getParentFile());
    request.setPom(pom);//  ww  w  .ja  v a 2 s  . co m
    request.setSystemProperties(systemProps);
    request.setUserProperties(userProps);
    request.setLocalRepository(getLocalRepository());

    request.setGoals(Arrays.asList("validate"));

    return request;
}

From source file:org.fusesource.ide.syndesis.extensions.tests.integration.SyndesisExtensionProjectCreatorRunnableIT.java

License:Open Source License

protected void launchBuild(IProgressMonitor monitor) throws CoreException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, 10);
    final IMaven maven = MavenPlugin.getMaven();
    IMavenExecutionContext context = maven.createExecutionContext();
    final MavenExecutionRequest request = context.getExecutionRequest();
    IFile pom = project.getFile("pom.xml");
    File pomFile = pom.getRawLocation().toFile();
    request.setPom(pomFile);/* ww w .  ja v  a  2s  .  co  m*/
    request.setGoals(Arrays.asList("clean", "verify"));
    request.setBaseDirectory(pomFile.getParentFile());
    request.setUpdateSnapshots(false);
    MavenExecutionResult result;

    try {
        result = context.execute(new ICallable<MavenExecutionResult>() {
            public MavenExecutionResult call(IMavenExecutionContext context, IProgressMonitor innerMonitor)
                    throws CoreException {
                return ((MavenImpl) maven).lookupComponent(Maven.class).execute(request);
            }
        }, subMonitor.split(10));
    } catch (CoreException ex) {
        result = null;
    }

    boolean buildOK = result != null && !result.hasExceptions();
    if (result != null) {
        for (Throwable t : result.getExceptions()) {
            SyndesisExtensionIntegrationTestsActivator.pluginLog().logError(t);
        }
    }
    assertThat(buildOK).isTrue();
}

From source file:org.jboss.demos.maven.classpath.deployer.ArtifactDependencyResolver.java

License:Open Source License

/**
 * Resolve the dependencies of a maven project.
 * /*from w  w w .  ja  v a 2s  .  c  o  m*/
 * @param mavenProject the file to the mvn project pom
 * @return the included artifacts
 * @throws Exception for any error
 */
public IncludedArtifacts resolveDependencies(File mavenProject) throws Exception {
    // Create and validate the configuration
    Configuration configuration = createConfiguration();
    // Create the embedder
    MavenEmbedder embedder = new MavenEmbedder(configuration);
    embedder.setLogger(logger);

    // Read classpath pom
    MavenProject project = embedder.readProject(mavenProject);

    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setBaseDirectory(project.getBasedir());

    MavenExecutionResult executionResult = embedder.readProjectWithDependencies(request);
    Set<Artifact> artifacts = executionResult.getArtifactResolutionResult().getArtifacts();

    // Process the project dependencies
    IncludedArtifacts included = new IncludedArtifacts();
    for (Artifact artifact : artifacts) {
        // Add the artifact 
        included.addArtifact(artifact);
    }
    return included;
}

From source file:org.jboss.tools.maven.polyglot.poc.internal.core.PomTranslatorJob.java

License:Open Source License

protected MavenExecutionResult translate(IFile pom, IFile input, IFile output, IProgressMonitor monitor)
        throws CoreException {
    final IMaven maven = MavenPlugin.getMaven();
    IMavenExecutionContext context = maven.createExecutionContext();
    final MavenExecutionRequest request = context.getExecutionRequest();
    File pomFile = pom.getRawLocation().toFile();
    request.setBaseDirectory(pomFile.getParentFile());
    request.setGoals(Arrays.asList("io.takari.polyglot:polyglot-translate-plugin:translate"));
    request.setUpdateSnapshots(false);//from  w w  w.ja v  a  2 s  .  co m
    Properties props = new Properties();
    props.put("input", input.getRawLocation().toOSString());
    String rawDestination = output.getRawLocation().toOSString();
    props.put("output", rawDestination);
    request.setUserProperties(props);

    new File(rawDestination).getParentFile().mkdirs();

    MavenExecutionResult result = context.execute(new ICallable<MavenExecutionResult>() {
        public MavenExecutionResult call(IMavenExecutionContext context, IProgressMonitor innerMonitor)
                throws CoreException {
            return ((MavenImpl) maven).lookupComponent(Maven.class).execute(request);
        }
    }, monitor);

    output.refreshLocal(IResource.DEPTH_ZERO, monitor);
    return result;
}

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

License:Apache License

protected MavenExecutionRequest populateRequest(AFCliRequest cliRequest, MavenExecutionRequest request) {

    CommandLine commandLine = cliRequest.getCommandLine();
    String workingDirectory = cliRequest.getWorkingDirectory();
    boolean quiet = cliRequest.isQuiet();
    boolean showErrors = cliRequest.isShowErrors();

    String[] deprecatedOptions = { "up", "npu", "cpu", "npr" };
    for (String deprecatedOption : deprecatedOptions) {
        if (commandLine.hasOption(deprecatedOption)) {
            slf4jLogger.warn("Command line option -" + deprecatedOption
                    + " is deprecated and will be removed in future Maven versions.");
        }/* www .j a v  a 2 s  . co m*/
    }

    // ----------------------------------------------------------------------
    // Now that we have everything that we need we will fire up plexus and
    // bring the maven component to life for use.
    // ----------------------------------------------------------------------

    if (commandLine.hasOption(CLIManager.BATCH_MODE)) {
        request.setInteractiveMode(false);
    }

    boolean noSnapshotUpdates = false;
    if (commandLine.hasOption(CLIManager.SUPRESS_SNAPSHOT_UPDATES)) {
        noSnapshotUpdates = true;
    }

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    @SuppressWarnings("unchecked")
    List<String> goals = commandLine.getArgList();

    boolean recursive = true;

    // this is the default behavior.
    String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;

    if (commandLine.hasOption(CLIManager.NON_RECURSIVE)) {
        recursive = false;
    }

    if (commandLine.hasOption(CLIManager.FAIL_FAST)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
    } else if (commandLine.hasOption(CLIManager.FAIL_AT_END)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END;
    } else if (commandLine.hasOption(CLIManager.FAIL_NEVER)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER;
    }

    if (commandLine.hasOption(CLIManager.OFFLINE)) {
        request.setOffline(true);
    }

    boolean updateSnapshots = false;

    if (commandLine.hasOption(CLIManager.UPDATE_SNAPSHOTS)) {
        updateSnapshots = true;
    }

    String globalChecksumPolicy = null;

    if (commandLine.hasOption(CLIManager.CHECKSUM_FAILURE_POLICY)) {
        globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
    } else if (commandLine.hasOption(CLIManager.CHECKSUM_WARNING_POLICY)) {
        globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN;
    }

    File baseDirectory = new File(workingDirectory, "").getAbsoluteFile();

    // ----------------------------------------------------------------------
    // Profile Activation
    // ----------------------------------------------------------------------

    List<String> activeProfiles = new ArrayList<String>();

    List<String> inactiveProfiles = new ArrayList<String>();

    if (commandLine.hasOption(CLIManager.ACTIVATE_PROFILES)) {
        String[] profileOptionValues = commandLine.getOptionValues(CLIManager.ACTIVATE_PROFILES);
        if (profileOptionValues != null) {
            for (String profileOptionValue : profileOptionValues) {
                StringTokenizer profileTokens = new StringTokenizer(profileOptionValue, ",");

                while (profileTokens.hasMoreTokens()) {
                    String profileAction = profileTokens.nextToken().trim();

                    if (profileAction.startsWith("-") || profileAction.startsWith("!")) {
                        inactiveProfiles.add(profileAction.substring(1));
                    } else if (profileAction.startsWith("+")) {
                        activeProfiles.add(profileAction.substring(1));
                    } else {
                        activeProfiles.add(profileAction);
                    }
                }
            }
        }
    }

    TransferListener transferListener;

    if (quiet) {
        transferListener = new QuietMavenTransferListener();
    } else if (request.isInteractiveMode() && !cliRequest.getCommandLine().hasOption(CLIManager.LOG_FILE)) {
        //
        // If we're logging to a file then we don't want the console transfer listener as it will spew
        // download progress all over the place
        //
        transferListener = getConsoleTransferListener();
    } else {
        transferListener = getBatchTransferListener();
    }

    ExecutionListener executionListener = new ExecutionEventLogger();

    if (eventSpyDispatcher != null) {
        executionListener = eventSpyDispatcher.chainListener(executionListener);
    }

    String alternatePomFile = null;
    if (commandLine.hasOption(CLIManager.ALTERNATE_POM_FILE)) {
        alternatePomFile = commandLine.getOptionValue(CLIManager.ALTERNATE_POM_FILE);
    }

    request.setBaseDirectory(baseDirectory).setGoals(goals)
            .setSystemProperties(cliRequest.getSystemProperties())
            .setUserProperties(cliRequest.getUserProperties())
            .setReactorFailureBehavior(reactorFailureBehaviour) // default: fail fast
            .setRecursive(recursive) // default: true
            .setShowErrors(showErrors) // default: false
            .addActiveProfiles(activeProfiles) // optional
            .addInactiveProfiles(inactiveProfiles) // optional
            .setExecutionListener(executionListener).setTransferListener(transferListener) // default: batch mode which goes along with interactive
            .setUpdateSnapshots(updateSnapshots) // default: false
            .setNoSnapshotUpdates(noSnapshotUpdates) // default: false
            .setGlobalChecksumPolicy(globalChecksumPolicy) // default: warn
            .setMultiModuleProjectDirectory(new File(cliRequest.getMultiModuleProjectDirectory()));

    if (alternatePomFile != null) {
        File pom = resolveFile(new File(alternatePomFile.trim()), workingDirectory);
        if (pom.isDirectory()) {
            pom = new File(pom, "pom.xml");
        }

        request.setPom(pom);
    } else if (modelProcessor != null) {
        File pom = modelProcessor.locatePom(baseDirectory);

        if (pom.isFile()) {
            request.setPom(pom);
        }
    }

    if ((request.getPom() != null) && (request.getPom().getParentFile() != null)) {
        request.setBaseDirectory(request.getPom().getParentFile());
    }

    if (commandLine.hasOption(CLIManager.RESUME_FROM)) {
        request.setResumeFrom(commandLine.getOptionValue(CLIManager.RESUME_FROM));
    }

    if (commandLine.hasOption(CLIManager.PROJECT_LIST)) {
        String[] projectOptionValues = commandLine.getOptionValues(CLIManager.PROJECT_LIST);

        List<String> inclProjects = new ArrayList<String>();
        List<String> exclProjects = new ArrayList<String>();

        if (projectOptionValues != null) {
            for (String projectOptionValue : projectOptionValues) {
                StringTokenizer projectTokens = new StringTokenizer(projectOptionValue, ",");

                while (projectTokens.hasMoreTokens()) {
                    String projectAction = projectTokens.nextToken().trim();

                    if (projectAction.startsWith("-") || projectAction.startsWith("!")) {
                        exclProjects.add(projectAction.substring(1));
                    } else if (projectAction.startsWith("+")) {
                        inclProjects.add(projectAction.substring(1));
                    } else {
                        inclProjects.add(projectAction);
                    }
                }
            }
        }

        request.setSelectedProjects(inclProjects);
        request.setExcludedProjects(exclProjects);
    }

    if (commandLine.hasOption(CLIManager.ALSO_MAKE)
            && !commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
    } else if (!commandLine.hasOption(CLIManager.ALSO_MAKE)
            && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM);
    } else if (commandLine.hasOption(CLIManager.ALSO_MAKE)
            && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_BOTH);
    }

    String localRepoProperty = request.getUserProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);

    if (localRepoProperty == null) {
        localRepoProperty = request.getSystemProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);
    }

    if (localRepoProperty != null) {
        request.setLocalRepositoryPath(localRepoProperty);
    }

    request.setCacheNotFound(true);
    request.setCacheTransferError(false);

    //
    // Builder, concurrency and parallelism
    //
    // We preserve the existing methods for builder selection which is to look for various inputs in the threading
    // configuration. We don't have an easy way to allow a pluggable builder to provide its own configuration
    // parameters but this is sufficient for now. Ultimately we want components like Builders to provide a way to
    // extend the command line to accept its own configuration parameters.
    //
    final String threadConfiguration = commandLine.hasOption(CLIManager.THREADS)
            ? commandLine.getOptionValue(CLIManager.THREADS)
            : request.getSystemProperties().getProperty(MavenCli.THREADS_DEPRECATED); // TODO: Remove this setting. Note that the int-tests use it

    if (threadConfiguration != null) {
        //
        // Default to the standard multithreaded builder
        //
        request.setBuilderId("multithreaded");

        if (threadConfiguration.contains("C")) {
            request.setDegreeOfConcurrency(calculateDegreeOfConcurrencyWithCoreMultiplier(threadConfiguration));
        } else {
            request.setDegreeOfConcurrency(Integer.valueOf(threadConfiguration));
        }
    }

    //
    // Allow the builder to be overriden by the user if requested. The builders are now pluggable.
    //
    if (commandLine.hasOption(CLIManager.BUILDER)) {
        request.setBuilderId(commandLine.getOptionValue(CLIManager.BUILDER));
    }

    return request;
}