Example usage for org.apache.maven.execution MavenExecutionResult getProject

List of usage examples for org.apache.maven.execution MavenExecutionResult getProject

Introduction

In this page you can find the example usage for org.apache.maven.execution MavenExecutionResult getProject.

Prototype

MavenProject getProject();

Source Link

Usage

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  ww.  j av  a2 s. c om

    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.soebes.maven.extensions.BuildTimeProfiler.java

License:Apache License

private void executionResultEventHandler(MavenExecutionResult event) {
    if (lifeCyclePhases.isEmpty()) {
        return;// w ww  .  ja va  2  s .com
    }

    orderLifeCycleOnPreparedOrder(lifeCyclePhases);

    LOGGER.debug("MBTP: executionResultEventHandler: {}", event.getProject());

    // TODO: Use better formatting
    LOGGER.info("--             Maven Build Time Profiler Summary                      --");
    LOGGER.info("------------------------------------------------------------------------");

    discoveryTimer.report();
    LOGGER.info("Project Build Time (reactor order):");
    LOGGER.info("");
    List<MavenProject> topologicallySortedProjects = event.getTopologicallySortedProjects();
    for (MavenProject mavenProject : topologicallySortedProjects) {
        LOGGER.info("{}:", mavenProject.getName());

        for (String phase : lifeCyclePhases) {
            ProjectKey proKey = mavenProjectToProjectKey(mavenProject);

            if (!mojoTimer.hasTimeForProjectAndPhase(proKey, phase)) {
                continue;
            }

            long timeForPhaseAndProjectInMillis = mojoTimer.getTimeForProjectAndPhaseInMillis(proKey, phase);
            LOGGER.info("    {} ms : {}", String.format("%8d", timeForPhaseAndProjectInMillis), phase);

        }

    }

    // LifecyclePhase.CLEAN.ordinal();
    LOGGER.info("------------------------------------------------------------------------");
    LOGGER.info("Lifecycle Phase summary:");
    LOGGER.info("");
    for (String phase : lifeCyclePhases) {
        long timeForPhaseInMillis = mojoTimer.getTimeForPhaseInMillis(phase);
        LOGGER.info("{} ms : {}", String.format("%8d", timeForPhaseInMillis), phase);
    }

    // List all plugins per phase
    LOGGER.info("------------------------------------------------------------------------");
    LOGGER.info("Plugins in lifecycle Phases:");
    LOGGER.info("");
    for (String phase : lifeCyclePhases) {
        LOGGER.info("{}:", phase);
        Map<ProjectMojo, SystemTime> plugisInPhase = mojoTimer.getPluginsInPhase(phase);
        for (Entry<ProjectMojo, SystemTime> pluginInPhase : plugisInPhase.entrySet()) {
            LOGGER.info("{} ms: {}", String.format("%8d", pluginInPhase.getValue().getElapsedTime()),
                    pluginInPhase.getKey().getMojo().getFullId());
        }

    }
    LOGGER.info("------------------------------------------------------------------------");

    installTimer.report();
    downloadTimer.report();
    deployTimer.report();
    metadataInstallTimer.report();
    metadataDownloadTimer.report();
    metadataDeploymentTimer.report();

    forkTimer.report();
    forkProject.report();
}

From source file:fitnesse.wikitext.widgets.Downloader.java

License:Apache License

public List<String> getArtifactAndDependencies(String pomUrl) throws MavenEmbedderException,
        XmlPullParserException, IOException, DependencyResolutionRequiredException, DownloadException {

    File pom = downloadPom(pomUrl);

    MavenEmbedder embedder = new MavenEmbedder(createConfiguration());

    Model model = embedder.readModel(pom);
    File tmpPom = createPomWithProjectAsDependency(pom, model);

    DefaultMavenExecutionRequest defaultMavenExecutionRequest = new DefaultMavenExecutionRequest();
    defaultMavenExecutionRequest.setUpdateSnapshots(true);
    MavenExecutionResult mavenResult = embedder
            .readProjectWithDependencies(defaultMavenExecutionRequest.setPom(tmpPom));

    List compileClasspathElements = mavenResult.getProject().getCompileClasspathElements();
    // little hack for now to remove source dir
    // TODO: find a way to have only jars elements, not sources elements
    compileClasspathElements.remove(0);/*  w  w w. ja  v  a2  s  .  co  m*/
    return compileClasspathElements;
}

From source file:fitnesse.wikitext.widgets.MavenClasspathWidget.java

License:Apache License

private List<String> getClasspathElements(Configuration configuration, MavenExecutionRequest request)
        throws MavenEmbedderException, DependencyResolutionRequiredException {
    MavenEmbedder embedder = new MavenEmbedder(configuration);
    MavenExecutionResult executionResult = embedder.readProjectWithDependencies(request);
    List<String> classpathElements = executionResult.getProject().getCompileClasspathElements();
    return classpathElements;
}

From source file:org.eclipse.m2e.core.internal.lifecyclemapping.discovery.LifecycleMappingConfiguration.java

License:Open Source License

static LifecycleMappingConfiguration calculate(Collection<MavenProjectInfo> projects,
        IProgressMonitor monitor) {//from ww  w  . j ava 2 s.  c o  m
    monitor.beginTask("Analysing project execution plan", projects.size());

    LifecycleMappingConfiguration result = new LifecycleMappingConfiguration();

    List<MavenProjectInfo> nonErrorProjects = new ArrayList<MavenProjectInfo>();
    final IMaven maven = MavenPlugin.getMaven();

    for (final MavenProjectInfo projectInfo : projects) {
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        MavenProject mavenProject = null;
        try {
            SubMonitor subMmonitor = SubMonitor.convert(monitor,
                    NLS.bind("Analysing {0}", projectInfo.getLabel()), 1);

            MavenExecutionResult executionResult = maven.execute(new ICallable<MavenExecutionResult>() {
                public MavenExecutionResult call(IMavenExecutionContext context, IProgressMonitor monitor)
                        throws CoreException {
                    return maven.readMavenProject(projectInfo.getPomFile(),
                            context.newProjectBuildingRequest());
                }
            }, subMmonitor);

            mavenProject = executionResult.getProject();

            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }

            if (mavenProject != null) {
                if ("pom".equals(projectInfo.getModel().getPackaging())) {
                    // m2e uses a noop lifecycle mapping for packaging=pom
                    List<MojoExecution> mojoExecutions = new ArrayList<MojoExecution>();
                    PackagingTypeMappingConfiguration pkgConfiguration = new PackagingTypeMappingConfiguration(
                            mavenProject.getPackaging(), null /*lifecycleMappingId*/);
                    ProjectLifecycleMappingConfiguration configuration = new ProjectLifecycleMappingConfiguration(
                            projectInfo.getLabel(), mavenProject, mojoExecutions, pkgConfiguration);
                    result.addProject(projectInfo, configuration);
                    nonErrorProjects.add(projectInfo);
                    continue;
                }

                List<MojoExecution> mojoExecutions = new ArrayList<MojoExecution>();
                MavenExecutionPlan executionPlan = maven.calculateExecutionPlan(mavenProject,
                        Arrays.asList(ProjectRegistryManager.LIFECYCLE_CLEAN), false, subMmonitor);
                mojoExecutions.addAll(executionPlan.getMojoExecutions());
                executionPlan = maven.calculateExecutionPlan(mavenProject,
                        Arrays.asList(ProjectRegistryManager.LIFECYCLE_DEFAULT), false, subMmonitor);
                mojoExecutions.addAll(executionPlan.getMojoExecutions());
                executionPlan = maven.calculateExecutionPlan(mavenProject,
                        Arrays.asList(ProjectRegistryManager.LIFECYCLE_SITE), false, subMmonitor);
                mojoExecutions.addAll(executionPlan.getMojoExecutions());

                LifecycleMappingResult lifecycleResult = new LifecycleMappingResult();

                List<MappingMetadataSource> metadataSources;
                try {
                    metadataSources = LifecycleMappingFactory.getProjectMetadataSources(mavenProject,
                            LifecycleMappingFactory.getBundleMetadataSources(), mojoExecutions, true, monitor);
                } catch (LifecycleMappingConfigurationException e) {
                    // could not read/parse/interpret mapping metadata configured in the pom or inherited from parent pom.
                    // record the problem and continue
                    log.error(e.getMessage(), e);
                    continue;
                }

                LifecycleMappingFactory.calculateEffectiveLifecycleMappingMetadata(lifecycleResult,
                        metadataSources, mavenProject, mojoExecutions, false, monitor);
                LifecycleMappingFactory.instantiateLifecycleMapping(lifecycleResult, mavenProject,
                        lifecycleResult.getLifecycleMappingId());
                LifecycleMappingFactory.instantiateProjectConfigurators(mavenProject, lifecycleResult,
                        lifecycleResult.getMojoExecutionMapping());

                PackagingTypeMappingConfiguration pkgConfiguration = new PackagingTypeMappingConfiguration(
                        mavenProject.getPackaging(),
                        isProjectSource(lifecycleResult.getLifecycleMappingMetadata())
                                ? lifecycleResult.getLifecycleMappingId()
                                : null);
                ProjectLifecycleMappingConfiguration configuration = new ProjectLifecycleMappingConfiguration(
                        projectInfo.getLabel(), mavenProject, mojoExecutions, pkgConfiguration);

                if (lifecycleResult.getLifecycleMapping() != null) {
                    result.addInstalledProvider(configuration.getPackagingTypeMappingConfiguration()
                            .getLifecycleMappingRequirement());
                }

                for (Map.Entry<MojoExecutionKey, List<IPluginExecutionMetadata>> entry : lifecycleResult
                        .getMojoExecutionMapping().entrySet()) {
                    MojoExecutionKey key = entry.getKey();
                    List<IPluginExecutionMetadata> mapppings = entry.getValue();
                    IPluginExecutionMetadata primaryMapping = null;
                    if (mapppings != null && !mapppings.isEmpty()) {
                        primaryMapping = mapppings.get(0);
                    }
                    MojoExecutionMappingConfiguration executionConfiguration = new MojoExecutionMappingConfiguration(
                            key, isProjectSource(primaryMapping) ? primaryMapping : null);
                    configuration.addMojoExecution(executionConfiguration);
                    if (primaryMapping != null) {
                        switch (primaryMapping.getAction()) {
                        case configurator:
                            AbstractProjectConfigurator projectConfigurator = lifecycleResult
                                    .getProjectConfigurators()
                                    .get(LifecycleMappingFactory.getProjectConfiguratorId(primaryMapping));
                            if (projectConfigurator != null) {
                                result.addInstalledProvider(
                                        executionConfiguration.getLifecycleMappingRequirement());
                            }
                            break;
                        case error:
                        case execute:
                        case ignore:
                            result.addInstalledProvider(
                                    executionConfiguration.getLifecycleMappingRequirement());
                            break;
                        default:
                            throw new IllegalArgumentException(
                                    "Missing handling for action=" + primaryMapping.getAction());
                        }
                    }
                }
                result.addProject(projectInfo, configuration);
                nonErrorProjects.add(projectInfo);
            } else {
                //XXX mkleint: what shall happen now? we don't have a valid MavenProject instance to play with,
                // currently we skip such project silently, is that ok?
            }

        } catch (OperationCanceledException ex) {
            throw ex;
        } catch (Throwable th) {
            result.addError(projectInfo, th);
        } finally {
            if (mavenProject != null) {
                ((MavenImpl) maven).releaseExtensionsRealm(mavenProject);
            }
        }
    }

    result.setSelectedProjects(nonErrorProjects);

    return result;
}

From source file:org.eclipse.m2e.core.internal.markers.MavenMarkerManager.java

License:Open Source License

public void addMarkers(IResource pomResource, String type, MavenExecutionResult result) {
    SourceLocation defaultSourceLocation = new SourceLocation(1, 0, 0);
    List<MavenProblemInfo> allProblems = new ArrayList<MavenProblemInfo>();

    allProblems.addAll(toMavenProblemInfos(pomResource, defaultSourceLocation, result.getExceptions()));

    MavenProject mavenProject = result.getProject();
    DependencyResolutionResult resolutionResult = result.getDependencyResolutionResult();
    if (resolutionResult != null) {
        allProblems.addAll(toMavenProblemInfos(pomResource, defaultSourceLocation,
                resolutionResult.getCollectionErrors()));
        for (org.sonatype.aether.graph.Dependency dependency : resolutionResult.getUnresolvedDependencies()) {
            List<Exception> exceptions = resolutionResult.getResolutionErrors(dependency);
            if (exceptions != null && exceptions.size() > 0) {
                SourceLocation sourceLocation = SourceLocationHelper.findLocation(mavenProject, dependency);
                allProblems.addAll(toMavenProblemInfos(pomResource, sourceLocation, exceptions));
            }//from   ww  w  . ja v a 2 s  . co  m
        }
    }

    if (mavenProject != null) {
        addMissingArtifactProblemInfos(mavenProject, defaultSourceLocation, allProblems);
    }

    addErrorMarkers(pomResource, type, allProblems);
}

From source file:org.eclipse.m2e.core.internal.project.registry.MavenProjectFacade.java

License:Open Source License

/**
 * Lazy load and cache MavenProject instance
 *///  www. j a va 2  s .c om
public synchronized MavenProject getMavenProject(IProgressMonitor monitor) throws CoreException {
    if (mavenProject == null) {
        MavenExecutionResult result = manager.readProjectWithDependencies(pom, resolverConfiguration, monitor);
        mavenProject = result.getProject();
        if (mavenProject == null) {
            MultiStatus status = new MultiStatus(IMavenConstants.PLUGIN_ID, 0,
                    Messages.MavenProjectFacade_error, null);
            List<Throwable> exceptions = result.getExceptions();
            for (Throwable e : exceptions) {
                status.add(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, 0, e.getMessage(), e));
            }
            throw new CoreException(status);
        }
    }
    return mavenProject;
}

From source file:org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.java

License:Open Source License

/**
 * Returns MavenProjectFacade corresponding to the pom. This method first looks in the project cache, then attempts to
 * load the pom if the pom is not found in the cache. In the latter case, workspace resolution is assumed to be
 * enabled for the pom but the pom will not be added to the cache.
 *///  w  w  w.j a va 2  s  . c  om
public MavenProjectFacade create(IFile pom, boolean load, IProgressMonitor monitor) {
    if (pom == null) {
        return null;
    }

    // MavenProjectFacade projectFacade = (MavenProjectFacade) workspacePoms.get(pom.getFullPath());
    MavenProjectFacade projectFacade = projectRegistry.getProjectFacade(pom);
    if (projectFacade == null && load) {
        ResolverConfiguration configuration = ResolverConfigurationIO
                .readResolverConfiguration(pom.getProject());
        MavenExecutionResult executionResult = readProjectWithDependencies(projectRegistry, pom, configuration,
                monitor);
        MavenProject mavenProject = executionResult.getProject();
        if (mavenProject != null) {
            projectFacade = new MavenProjectFacade(this, pom, mavenProject, null, configuration);
        } else {
            List<Throwable> exceptions = executionResult.getExceptions();
            if (exceptions != null) {
                for (Throwable ex : exceptions) {
                    String msg = "Failed to read Maven project: " + ex.getMessage();
                    log.error(msg, ex);
                }
            }
        }
    }
    return projectFacade;
}

From source file:org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.java

License:Open Source License

private MavenProjectFacade readMavenProjectFacade(final IFile pom, DependencyResolutionContext context,
        final MutableProjectRegistry state, final IProgressMonitor monitor) throws CoreException {
    markerManager.deleteMarkers(pom, IMavenConstants.MARKER_POM_LOADING_ID);

    final ResolverConfiguration resolverConfiguration = ResolverConfigurationIO
            .readResolverConfiguration(pom.getProject());

    return execute(state, pom, resolverConfiguration, new ICallable<MavenProjectFacade>() {
        public MavenProjectFacade call(IMavenExecutionContext context, IProgressMonitor monitor)
                throws CoreException {
            MavenProject mavenProject = null;
            MavenExecutionResult mavenResult = null;
            if (pom.isAccessible()) {
                mavenResult = getMaven().readMavenProject(pom.getLocation().toFile(),
                        context.newProjectBuildingRequest());
                mavenProject = mavenResult.getProject();
            }// w w  w  .j  a v a2  s  . co  m

            MarkerUtils.addEditorHintMarkers(markerManager, pom, mavenProject,
                    IMavenConstants.MARKER_POM_LOADING_ID);
            markerManager.addMarkers(pom, IMavenConstants.MARKER_POM_LOADING_ID, mavenResult);
            if (mavenProject == null) {
                return null;
            }

            // don't cache maven session
            getMaven().detachFromSession(mavenProject);

            final MavenSession mavenSession = context.getSession();
            final MavenProject origCurrentProject = mavenSession.getCurrentProject();
            try {
                mavenSession.setCurrentProject(mavenProject);
                Map<String, List<MojoExecution>> executionPlans = calculateExecutionPlans(pom, mavenProject,
                        monitor);

                // create and return new project facade
                MavenProjectFacade mavenProjectFacade = new MavenProjectFacade(ProjectRegistryManager.this, pom,
                        mavenProject, executionPlans, resolverConfiguration);
                return mavenProjectFacade;
            } finally {
                mavenSession.setCurrentProject(origCurrentProject);
            }
        }
    }, monitor);
}

From source file:org.eclipse.m2e.core.ui.internal.actions.SelectionUtil.java

License:Open Source License

private static MavenProject readMavenProject(final File pomFile, IProgressMonitor monitor)
        throws CoreException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }//from  w  w w  .  jav a 2 s.c  om

    final IMaven maven = MavenPlugin.getMaven();

    IMavenExecutionContext context = maven.createExecutionContext();
    MavenExecutionRequest request = context.getExecutionRequest();
    request.setOffline(false);
    request.setUpdateSnapshots(false);
    request.setRecursive(false);

    MavenExecutionResult result = context.execute(new ICallable<MavenExecutionResult>() {
        public MavenExecutionResult call(IMavenExecutionContext context, IProgressMonitor monitor)
                throws CoreException {
            return maven.readMavenProject(pomFile, context.newProjectBuildingRequest());
        }
    }, monitor);

    MavenProject project = result.getProject();
    if (project != null) {
        return project;
    }

    if (result.hasExceptions()) {
        List<IStatus> statuses = new ArrayList<IStatus>();
        List<Throwable> exceptions = result.getExceptions();
        for (Throwable e : exceptions) {
            statuses.add(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1, e.getMessage(), e));
        }

        throw new CoreException(new MultiStatus(IMavenConstants.PLUGIN_ID, IStatus.ERROR, //
                statuses.toArray(new IStatus[statuses.size()]), Messages.SelectionUtil_error_cannot_read,
                null));
    }

    throw new CoreException(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1, //
            Messages.SelectionUtil_error_cannot_read, null));
}