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

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

Introduction

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

Prototype

Properties getUserProperties();

Source Link

Document

Gets the user properties to use for interpolation and profile activation.

Usage

From source file:io.sundr.maven.AbstractSundrioMojo.java

License:Apache License

void backGroundBuild(MavenProject project) throws MojoExecutionException {
    MavenExecutionRequest executionRequest = session.getRequest();

    InvocationRequest request = new DefaultInvocationRequest();
    request.setBaseDirectory(project.getBasedir());
    request.setPomFile(project.getFile());
    request.setGoals(executionRequest.getGoals());
    request.setRecursive(false);/*from   w ww  .ja v a2  s.c o m*/
    request.setInteractive(false);

    request.setProfiles(executionRequest.getActiveProfiles());
    request.setProperties(executionRequest.getUserProperties());
    Invoker invoker = new DefaultInvoker();
    try {
        InvocationResult result = invoker.execute(request);
        if (result.getExitCode() != 0) {
            throw new IllegalStateException(
                    "Error invoking Maven goals:[" + StringUtils.join(executionRequest.getGoals(), ", ") + "]",
                    result.getExecutionException());
        }
    } catch (MavenInvocationException e) {
        throw new IllegalStateException(
                "Error invoking Maven goals:[" + StringUtils.join(executionRequest.getGoals(), ", ") + "]", e);
    }
}

From source file:io.takari.maven.testing.Maven30xRuntime.java

License:Open Source License

@SuppressWarnings("deprecation")
protected MavenExecutionRequest newExecutionRequest() throws Exception {

    // system properties
    Properties buildProperties = getMavenBuildProperties();
    String mavenVersion = buildProperties.getProperty("version");
    Properties systemProperties = new Properties();
    systemProperties.putAll(System.getProperties()); // TODO not thread safe
    systemProperties.setProperty("maven.version", mavenVersion);
    systemProperties.setProperty("maven.build.version", mavenVersion);

    // request with initial configuration
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setLocalRepositoryPath(properties.getLocalRepository());
    request.setUserSettingsFile(properties.getUserSettings());
    request.setGlobalSettingsFile(properties.getGlobalSettings());
    request.setOffline(properties.getOffline());
    request.setUpdateSnapshots(properties.getUpdateSnapshots());
    request.setSystemProperties(systemProperties);

    // read settings
    SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
    settingsRequest.setGlobalSettingsFile(request.getGlobalSettingsFile());
    settingsRequest.setUserSettingsFile(request.getUserSettingsFile());
    settingsRequest.setSystemProperties(request.getSystemProperties());
    settingsRequest.setUserProperties(request.getUserProperties());
    Settings settings = lookup(SettingsBuilder.class).build(settingsRequest).getEffectiveSettings();

    MavenExecutionRequestPopulator populator = container.lookup(MavenExecutionRequestPopulator.class);
    request = populator.populateFromSettings(request, settings);
    return populator.populateDefaults(request);
}

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 a2s  .  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.eclipse.m2e.core.internal.embedder.MavenImpl.java

License:Open Source License

MavenExecutionRequest createExecutionRequest() throws CoreException {
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();

    // this causes problems with unexpected "stale project configuration" error markers
    // need to think how to manage ${maven.build.timestamp} properly inside workspace
    //request.setStartTime( new Date() );

    if (mavenConfiguration.getGlobalSettingsFile() != null) {
        request.setGlobalSettingsFile(new File(mavenConfiguration.getGlobalSettingsFile()));
    }/*from  w w  w  .java  2s .c  o  m*/
    if (mavenConfiguration.getUserSettingsFile() != null) {
        request.setUserSettingsFile(new File(mavenConfiguration.getUserSettingsFile()));
    }

    try {
        lookup(MavenExecutionRequestPopulator.class).populateFromSettings(request, getSettings());
    } catch (MavenExecutionRequestPopulationException ex) {
        throw new CoreException(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1,
                Messages.MavenImpl_error_no_exec_req, ex));
    }

    ArtifactRepository localRepository = getLocalRepository();
    request.setLocalRepository(localRepository);
    request.setLocalRepositoryPath(localRepository.getBasedir());
    request.setOffline(mavenConfiguration.isOffline());

    request.getUserProperties().put("m2e.version", MavenPluginActivator.getVersion()); //$NON-NLS-1$
    request.getUserProperties().put(ConfigurationProperties.USER_AGENT, MavenPluginActivator.getUserAgent());

    EnvironmentUtils.addEnvVars(request.getSystemProperties());
    request.getSystemProperties().putAll(System.getProperties());

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

    // the right way to disable snapshot update
    // request.setUpdateSnapshots(false);
    return request;
}

From source file:org.eclipse.tycho.testing.AbstractTychoMojoTestCase.java

License:Open Source License

protected List<MavenProject> getSortedProjects(File basedir, Properties userProperties, File platform)
        throws Exception {
    File pom = new File(basedir, "pom.xml");
    MavenExecutionRequest request = newMavenExecutionRequest(pom);
    request.getProjectBuildingRequest().setProcessPlugins(false);
    request.setLocalRepository(getLocalRepository());
    if (platform != null) {
        request.getUserProperties().put("tycho.targetPlatform", platform.getCanonicalPath());
    }//from w  w w  . jav a  2 s. c om
    if (userProperties != null) {
        request.getUserProperties().putAll(userProperties);
    }
    MavenExecutionResult result = maven.execute(request);
    if (result.hasExceptions()) {
        throw new CompoundRuntimeException(result.getExceptions());
    }
    return result.getTopologicallySortedProjects();
}

From source file:org.jboss.shrinkwrap.resolver.plugin.PropagateExecutionContextMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {

    MavenExecutionRequest request = session.getRequest();

    Properties properties = request.getUserProperties();

    // set pom file
    File pom = session.getCurrentProject().getFile();
    if (pom != null) {
        updateUserProperty(properties, "pom-file", pom.getAbsolutePath());
    }/*from ww w .  ja  v a  2 s.  c o  m*/

    // set offline flag
    updateUserProperty(properties, "offline", String.valueOf(session.isOffline()));

    // set settings.xml files
    File userSettings = request.getUserSettingsFile();
    if (userSettings != null) {
        updateUserProperty(properties, "user-settings", userSettings.getAbsolutePath());
    }
    File globalSettings = request.getGlobalSettingsFile();
    if (globalSettings != null) {
        updateUserProperty(properties, "global-settings", globalSettings.getAbsolutePath());
    }

    // set active profiles
    List<Profile> profiles = session.getCurrentProject().getActiveProfiles();
    StringBuilder sb = new StringBuilder();
    for (Profile p : profiles) {
        sb.append(p.getId()).append(",");
    }

    if (sb.length() > 0) {
        updateUserProperty(properties, "active-profiles", sb.substring(0, sb.length() - 1).toString());
    }

    request.setUserProperties(properties);
}

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.");
        }/*from w  w w.  j a v  a2s  .  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;
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.ReusableAFMavenCli.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)) {
            reusableSlf4jLogger.warn("Command line option -" + deprecatedOption
                    + " is deprecated and will be removed in future Maven versions.");
        }/*ww w.j ava 2  s .c o  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 (reusableEventSpyDispatcher != null) {
        executionListener = reusableEventSpyDispatcher.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 (reusableModelProcessor != null) {
        File pom = reusableModelProcessor.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;
}

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

License:Apache License

private void clearProperties(MavenExecutionRequest request) {
    request.getGoals().clear();// ww w . j  av  a 2 s  .com
    request.getUserProperties().clear();
    request.getActiveProfiles().clear();
    request.getInactiveProfiles().clear();
}

From source file:org.phpmaven.test.AbstractTestCase.java

License:Apache License

protected MavenData createProjectBuildingRequest() throws Exception {
    final File localReposFile = this.getLocalReposDir();

    final SimpleLocalRepositoryManager localRepositoryManager = new SimpleLocalRepositoryManager(
            localReposFile);// w  ww. j a va2s . c o m

    final DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
    for (final Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
        repositorySession.getSystemProperties().put(entry.getKey().toString(), entry.getValue().toString());
    }
    repositorySession.getSystemProperties().put("java.version", System.getProperty("java.version"));
    repositorySession.setDependencyGraphTransformer(
            new ChainedDependencyGraphTransformer(new ConflictMarker(), new JavaEffectiveScopeCalculator(),
                    new NearestVersionConflictResolver(), new JavaDependencyContextRefiner()));
    final MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    final MavenExecutionRequestPopulator populator = lookup(MavenExecutionRequestPopulator.class);
    populator.populateDefaults(request);

    final SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
    settingsRequest.setGlobalSettingsFile(MavenCli.DEFAULT_GLOBAL_SETTINGS_FILE);
    settingsRequest.setUserSettingsFile(MavenCli.DEFAULT_USER_SETTINGS_FILE);
    settingsRequest.setSystemProperties(request.getSystemProperties());
    settingsRequest.setUserProperties(request.getUserProperties());
    final SettingsBuilder settingsBuilder = lookup(SettingsBuilder.class);
    final SettingsBuildingResult settingsResult = settingsBuilder.build(settingsRequest);
    final MavenExecutionRequestPopulator executionRequestPopulator = lookup(
            MavenExecutionRequestPopulator.class);
    executionRequestPopulator.populateFromSettings(request, settingsResult.getEffectiveSettings());

    final ArtifactRepositoryLayout layout = lookup(ArtifactRepositoryLayout.class);
    final ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy();
    final MavenArtifactRepository repos = new MavenArtifactRepository("local",
            localReposFile.toURI().toURL().toString(), layout, policy, policy);

    request.setLocalRepository(repos);
    request.setSystemProperties(new Properties(System.getProperties()));
    request.getSystemProperties().put("java.version", System.getProperty("java.version"));
    repositorySession.setLocalRepositoryManager(localRepositoryManager);

    final ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest();
    buildingRequest.setLocalRepository(request.getLocalRepository());
    buildingRequest.setRepositorySession(repositorySession);
    buildingRequest.setSystemProperties(request.getSystemProperties());
    buildingRequest.getRemoteRepositories().addAll(request.getRemoteRepositories());
    buildingRequest.setProfiles(request.getProfiles());
    buildingRequest.setActiveProfileIds(request.getActiveProfiles());
    buildingRequest.setProcessPlugins(false);
    buildingRequest.setResolveDependencies(false);

    final MavenData data = new MavenData();
    data.executionRequest = request;
    data.projectBuildingRequest = buildingRequest;

    return data;
}