Example usage for org.apache.maven.project MavenProject getModel

List of usage examples for org.apache.maven.project MavenProject getModel

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getModel.

Prototype

public Model getModel() 

Source Link

Usage

From source file:org.sonatype.nexus.plugin.deploy.DeployLifecycleParticipant.java

License:Open Source License

public void afterProjectsRead(final MavenSession session) throws MavenExecutionException {
    try {//from w  w  w . j av a2 s  . c o  m
        // check do we need to do anything at all?
        // should not find any nexus-maven-plugin deploy goal executions in any project
        // otherwise, assume it's "manually done"
        for (MavenProject project : session.getProjects()) {
            final Plugin nexusMavenPlugin = getBuildPluginsNexusMavenPlugin(project.getModel());
            if (nexusMavenPlugin != null) {
                if (!nexusMavenPlugin.getExecutions().isEmpty()) {
                    for (PluginExecution pluginExecution : nexusMavenPlugin.getExecutions()) {
                        final List<String> goals = pluginExecution.getGoals();
                        if (goals.contains("deploy") || goals.contains("deploy-staged")
                                || goals.contains("staging-close") || goals.contains("staging-release")
                                || goals.contains("staging-promote")) {
                            logger.info(
                                    "Not installing Nexus Staging features, some Staging related goal bindings already present.");
                            return;
                        }
                    }
                }
            }
        }

        logger.info("Installing Nexus Staging features:");

        // make maven-deploy-plugin to be skipped and install us instead
        int skipped = 0;
        for (MavenProject project : session.getProjects()) {
            final Plugin nexusMavenPlugin = getBuildPluginsNexusMavenPlugin(project.getModel());
            if (nexusMavenPlugin != null) {
                // skip the maven-deploy-plugin
                final Plugin mavenDeployPlugin = getBuildPluginsMavenDeployPlugin(project.getModel());
                if (mavenDeployPlugin != null) {
                    // TODO: better would be to remove them targeted?
                    // But this mojo has only 3 goals, but only one of them is usable in builds ("deploy")
                    mavenDeployPlugin.getExecutions().clear();

                    // add executions to nexus-maven-plugin
                    final PluginExecution execution = new PluginExecution();
                    execution.setId("injected-nexus-deploy");
                    execution.getGoals().add("deploy");
                    execution.setPhase("deploy");
                    execution.setConfiguration(nexusMavenPlugin.getConfiguration());
                    nexusMavenPlugin.getExecutions().add(execution);

                    // count this in
                    skipped++;
                }
            }
        }
        if (skipped > 0) {
            logger.info("  ... total of " + skipped
                    + " executions of maven-deploy-plugin replaced with nexus-maven-plugin.");
        }
    } catch (IllegalStateException e) {
        // thrown by getPluginByGAFromContainer
        throw new MavenExecutionException(e.getMessage(), e);
    }
}

From source file:org.sonatype.nexus.plugin.discovery.DefaultNexusDiscovery.java

License:Open Source License

private void collectForDiscovery(final Settings settings, final MavenProject project,
        final List<NexusConnectionInfo> candidates, final List<ServerMapping> serverMap,
        final Map<String, Server> serversById) throws NexusDiscoveryException {
    if (project != null && project.getDistributionManagement() != null && project.getArtifact() != null) {
        DistributionManagement distMgmt = project.getDistributionManagement();
        DeploymentRepository repo = distMgmt.getRepository();
        if (project.getArtifact().isSnapshot() && distMgmt.getSnapshotRepository() != null) {
            repo = distMgmt.getSnapshotRepository();
        }/*ww w . j  av a2 s  .c om*/

        if (repo != null) {
            String id = repo.getId();
            String url = repo.getUrl();
            addCandidate(id, url, repo.getName(), serversById, candidates, serverMap);
        }
    }

    if (settings != null && settings.getMirrors() != null) {
        for (Mirror mirror : settings.getMirrors()) {
            addCandidate(mirror.getId(), mirror.getUrl(), mirror.getName(), serversById, candidates, serverMap);
        }
    }

    if (project != null) {
        if (project.getModel().getRepositories() != null) {
            for (Repository repo : project.getModel().getRepositories()) {
                addCandidate(repo.getId(), repo.getUrl(), repo.getName(), serversById, candidates, serverMap);
            }
        }

        if (project.getModel().getProfiles() != null) {
            for (Profile profile : project.getModel().getProfiles()) {
                for (Repository repo : profile.getRepositories()) {
                    addCandidate(repo.getId(), repo.getUrl(), repo.getName(), serversById, candidates,
                            serverMap);
                }
            }
        }
    }

    if (settings != null && settings.getProfiles() != null) {
        for (org.apache.maven.settings.Profile profile : settings.getProfiles()) {
            if (profile != null && profile.getRepositories() != null) {
                for (org.apache.maven.settings.Repository repo : profile.getRepositories()) {
                    addCandidate(repo.getId(), repo.getUrl(), repo.getName(), serversById, candidates,
                            serverMap);
                }
            }
        }
    }
}

From source file:org.sourcepit.common.maven.core.MavenProjectUtils.java

License:Apache License

private static ArtifactRepository getDistributionManagementRepository(MavenProject project, String version) {
    final MavenProject clone = project.clone();
    clone.setVersion(version);/* w w w .  jav a  2 s .co  m*/
    clone.getModel().setVersion(version);
    clone.getArtifact().setVersion(version);
    return clone.getDistributionManagementArtifactRepository();
}

From source file:org.sourcepit.maven.dependency.model.aether.AetherDependencyModelResolver.java

License:Apache License

/**
 * {@inheritDoc}/* w  ww. j a va 2s  .  c  o m*/
 */
@Override
public DependencyModel resolve(@NotNull Collection<Dependency> dependencies,
        ArtifactAttachmentFactory attachmentFactory)
        throws ProjectBuildingException, DependencyResolutionException {
    final Model model;

    final MavenProject currentProject = buildContext.getSession().getCurrentProject();
    if (currentProject == null) {
        model = new Model();
    } else {
        model = currentProject.getModel().clone();
    }

    model.setModelVersion("4.0.0");
    model.setGroupId("org.sourcepit");
    model.setArtifactId("dummy-project");
    model.setVersion("1337");

    model.getDependencies().clear();
    model.getDependencies().addAll(dependencies);

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        new DefaultModelWriter().write(out, null, model);
    } catch (IOException e) {
        throw Exceptions.pipe(e);
    }
    final byte[] bytes = out.toByteArray();

    final ProjectBuildingRequest request = newProjectBuildingRequest(false, false);

    ProjectBuildingResult result = projectBuilder.build(new ModelSource() {
        @Override
        public String getLocation() {
            return "memory";
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(bytes);
        }
    }, request);

    final MavenProject project = result.getProject();
    return resolve(project, false, attachmentFactory);
}

From source file:org.sourcepit.osgifier.maven.OsgifyArtifactsMojo.java

License:Apache License

@Override
protected void doExecute() throws MojoExecutionException, MojoFailureException {
    final PropertiesSource options = MojoUtils
            .getOptions(buildContext.getSession().getCurrentProject().getProperties(), this.options);
    final Date startTime = buildContext.getSession().getStartTime();

    final OsgifierContext osgifyContext = modelBuilder.build(new DefaultOsgifierContextInflatorFilter(),
            options, artifacts, startTime);

    final Collection<BundleCandidate> bundles = new ArrayList<BundleCandidate>();
    for (BundleCandidate bundle : osgifyContext.getBundles()) {
        if (!bundle.isNativeBundle() && bundle.getTargetBundle() == null) {
            bundles.add(bundle);// w  w w  . jav  a2  s. c o m
        }
    }

    final DependencyModel dependencyModel = osgifyContext.getExtension(DependencyModel.class);

    final Map<BundleCandidate, MavenProject> mavenProjectMapping = new HashMap<BundleCandidate, MavenProject>(
            bundles.size());

    for (BundleCandidate bundle : bundles) {
        final MavenArtifact artifact = bundle.getExtension(MavenArtifact.class);

        try {
            ProjectBuildingResult result = buildMavenProject(artifact);
            mavenProjectMapping.put(bundle, result.getProject());
        } catch (ProjectBuildingException e) {
            getLog().warn(String.format(
                    "Failed to resolve original Maven model for artifact %s. Some information may note be available in genrated pom.",
                    artifact), e);
        }

        adoptMavenCoordinates(dependencyModel, bundle);
        final BundleCandidate sourceBundle = bundle.getSourceBundle();
        if (sourceBundle != null) {
            adoptMavenCoordinates(dependencyModel, sourceBundle);
        }
    }

    for (BundleCandidate bundle : bundles) {
        injectManifest(dependencyModel, bundle);
        final BundleCandidate sourceBundle = bundle.getSourceBundle();
        if (sourceBundle != null) {
            injectManifest(dependencyModel, sourceBundle);
        }
    }

    ModelUtils.writeModel(getOsgifierContextFile(), osgifyContext);

    final Collection<Artifact> artifacts = new ArrayList<Artifact>();
    for (BundleCandidate bundle : bundles) {
        final MavenArtifact bundleArtifact = bundle.getExtension(MavenArtifact.class);
        final Artifact artifact = artifactFactory.createArtifact(bundleArtifact.getArtifactKey())
                .setFile(bundle.getLocation());
        artifacts.add(artifact);

        final BundleCandidate sourceBundle = bundle.getSourceBundle();
        if (sourceBundle != null) {
            final Artifact sourceArtifact = artifactFactory.createArtifact(artifact, "sources", "jar")
                    .setFile(sourceBundle.getLocation());
            artifacts.add(sourceArtifact);
        }

        final Model model = buildPom(bundle, dependencyModel);

        final MavenProject mavenProject = mavenProjectMapping.get(bundle);
        if (mavenProject != null) {
            final Model oriModel = mavenProject.getModel();

            model.setCiManagement(oriModel.getCiManagement());
            model.setContributors(oriModel.getContributors());
            model.setDescription(oriModel.getDescription());
            model.setDevelopers(oriModel.getDevelopers());
            model.setInceptionYear(oriModel.getInceptionYear());
            model.setLicenses(oriModel.getLicenses());
            model.setMailingLists(oriModel.getMailingLists());
            model.setName(oriModel.getName());
            model.setOrganization(oriModel.getOrganization());
            model.setScm(oriModel.getScm());
            model.setUrl(oriModel.getUrl());
        }

        final File pomFile = new File(workDir, getBundleId(bundle) + ".xml");
        try {
            new DefaultModelWriter().write(pomFile, null, model);
        } catch (IOException e) {
            throw pipe(e);
        }

        final Artifact pomArtifact = artifactFactory.createArtifact(artifact, null, "pom").setFile(pomFile);
        artifacts.add(pomArtifact);
    }

    MavenProject project = buildContext.getSession().getCurrentProject();
    project.setContextValue("osgified-artifacts", artifacts);

    printSummary(artifacts);
}

From source file:org.sourcepit.tpmp.resolver.tycho.TychoSessionTargetPlatformResolver.java

License:Apache License

private MavenProject setupAggregatedProject(MavenSession session,
        TargetPlatformConfiguration aggregatedConfiguration) {
    PropertiesMap mvnProperties = new LinkedPropertiesMap();
    mvnProperties.load(getClass().getClassLoader(), "META-INF/tpmp/maven.properties");

    String groupId = mvnProperties.get("groupId");
    String artifactId = mvnProperties.get("artifactId");
    String version = mvnProperties.get("version");

    final String tpmpKey = Plugin.constructKey(groupId, artifactId);

    MavenProject origin = session.getCurrentProject();

    Model model = origin.getModel().clone();
    Build build = model.getBuild();/*from  w  w w . ja va  2s . c om*/
    if (build.getPluginsAsMap().get(tpmpKey) == null) {
        Plugin tpmp = new Plugin();
        tpmp.setGroupId(groupId);
        tpmp.setArtifactId(artifactId);
        tpmp.setVersion(version);

        build.getPlugins().add(tpmp);
        build.flushPluginMap();
    }

    MavenProject fake = new MavenProject(model);
    fake.setClassRealm(origin.getClassRealm());
    fake.setFile(origin.getFile());

    final Map<String, ArtifactRepository> artifactRepositories = new LinkedHashMap<String, ArtifactRepository>();
    final Map<String, ArtifactRepository> pluginRepositories = new LinkedHashMap<String, ArtifactRepository>();
    for (MavenProject project : session.getProjects()) {
        for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
            if (!artifactRepositories.containsKey(repository.getId())) {
                artifactRepositories.put(repository.getId(), repository);
            }
        }
        for (ArtifactRepository repository : project.getPluginArtifactRepositories()) {
            if (!pluginRepositories.containsKey(repository.getId())) {
                pluginRepositories.put(repository.getId(), repository);
            }
        }
    }

    fake.setRemoteArtifactRepositories(new ArrayList<ArtifactRepository>(artifactRepositories.values()));
    fake.setPluginArtifactRepositories(new ArrayList<ArtifactRepository>(pluginRepositories.values()));
    fake.setManagedVersionMap(origin.getManagedVersionMap());

    if (getTychoProject(fake) == null) {
        fake.setPackaging("eclipse-repository");
    }

    fake.getBuildPlugins();

    AbstractTychoProject tychoProject = (AbstractTychoProject) getTychoProject(fake);
    tychoProject.setupProject(session, fake);

    Properties properties = new Properties();
    properties.putAll(fake.getProperties());
    properties.putAll(session.getSystemProperties()); // session wins
    properties.putAll(session.getUserProperties());
    fake.setContextValue(TychoConstants.CTX_MERGED_PROPERTIES, properties);

    fake.setContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION, aggregatedConfiguration);

    ExecutionEnvironmentConfiguration eeConfiguration = new ExecutionEnvironmentConfigurationImpl(logger,
            aggregatedConfiguration.isResolveWithEEConstraints());
    tychoProject.readExecutionEnvironmentConfiguration(fake, eeConfiguration);
    fake.setContextValue(TychoConstants.CTX_EXECUTION_ENVIRONMENT_CONFIGURATION, eeConfiguration);

    final DependencyMetadata dm = new DependencyMetadata();
    for (ReactorProject reactorProject : DefaultReactorProject.adapt(session)) {
        mergeMetadata(dm, reactorProject, true);
        mergeMetadata(dm, reactorProject, false);
    }

    int i = 0;
    for (Object object : dm.getMetadata(true)) {
        InstallableUnitDAO dao = new TychoSourceIUResolver.InstallableUnitDAO(
                object.getClass().getClassLoader());
        dao.setProperty(object, RepositoryLayoutHelper.PROP_CLASSIFIER, "fake_" + i);
        i++;
    }

    for (Object object : dm.getMetadata(false)) {
        InstallableUnitDAO dao = new TychoSourceIUResolver.InstallableUnitDAO(
                object.getClass().getClassLoader());
        dao.setProperty(object, RepositoryLayoutHelper.PROP_CLASSIFIER, "fake_" + i);
        i++;
    }

    Map<String, DependencyMetadata> metadata = new LinkedHashMap<String, DependencyMetadata>();
    metadata.put(null, dm);

    fake.setContextValue("tpmp.aggregatedMetadata", metadata);

    return fake;
}

From source file:org.springframework.ide.vscode.commons.maven.java.MavenProjectClasspath.java

License:Open Source License

private ImmutableList<CPE> resolveClasspathEntries(MavenProject project) throws Exception {
    LinkedHashSet<CPE> entries = new LinkedHashSet<>();
    safe(() -> maven.getJreLibs().forEach(path -> safe(() -> {
        CPE cpe = CPE.binary(path.toString());
        String javaVersion = maven.getJavaRuntimeMinorVersion();
        if (javaVersion == null) {
            javaVersion = "8";
        }//w ww  .  j  a v  a2 s . c  om
        cpe.setJavadocContainerUrl(new URL("https://docs.oracle.com/javase/" + javaVersion + "/docs/api/"));
        cpe.setSystem(true);
        entries.add(cpe);
        // Add at the end, not critical if throws exception, but the CPE needs to be around regardless if the below throws
        Path sources = JavaUtils.jreSources(path);
        if (sources != null) {
            cpe.setSourceContainerUrl(sources.toUri().toURL());
        }
    })));
    //Add jar dependencies...
    for (Artifact a : projectDependencies(project)) {
        File f = a.getFile();
        if (f != null) {
            CPE cpe = CPE.binary(a.getFile().toPath().toString());
            safe(() -> { //add javadoc
                Artifact jdoc = maven.getJavadoc(a, project.getRemoteArtifactRepositories());
                if (jdoc != null) {
                    cpe.setJavadocContainerUrl(jdoc.getFile().toURI().toURL());
                }
            });
            safe(() -> { //add source
                Artifact source = maven.getSources(a, project.getRemoteArtifactRepositories());
                if (source != null) {
                    cpe.setSourceContainerUrl(source.getFile().toURI().toURL());
                }
            });
            entries.add(cpe);
        }
    }
    //Add source folders...
    { //main/java
        File sourceFolder = new File(project.getBuild().getSourceDirectory());
        File outputFolder = new File(project.getBuild().getOutputDirectory());
        CPE cpe = CPE.source(sourceFolder, outputFolder);
        cpe.setOwn(true);
        safe(() -> {
            String reportingDir = project.getModel().getReporting().getOutputDirectory();
            if (reportingDir != null) {
                File apidocs = new File(new File(reportingDir), "apidocs");
                cpe.setJavadocContainerUrl(apidocs.toURI().toURL());
            }
        });
        entries.add(cpe);
    }
    { //main/resources
        for (Resource resource : project.getBuild().getResources()) {
            File sourceFolder = new File(resource.getDirectory());
            String targetPath = resource.getTargetPath();
            if (targetPath == null) {
                targetPath = project.getBuild().getOutputDirectory();
            }
            CPE cpe = CPE.source(sourceFolder, new File(targetPath));
            cpe.setOwn(true);
            entries.add(cpe);
        }
    }
    { //test/resources
        for (Resource resource : project.getBuild().getTestResources()) {
            File sourceFolder = new File(resource.getDirectory());
            String targetPath = resource.getTargetPath();
            if (targetPath == null) {
                targetPath = project.getBuild().getTestOutputDirectory();
            }
            CPE cpe = CPE.source(sourceFolder, targetPath == null ? null : new File(targetPath));
            cpe.setOwn(true);
            entries.add(cpe);
        }
    }
    { //test/java
        File sourceFolder = new File(project.getBuild().getTestSourceDirectory());
        File outputFolder = new File(project.getBuild().getTestOutputDirectory());
        CPE cpe = CPE.source(sourceFolder, outputFolder);
        cpe.setOwn(true);
        safe(() -> {
            String reportingDir = project.getModel().getReporting().getOutputDirectory();
            if (reportingDir != null) {
                File apidocs = new File(new File(reportingDir), "apidocs");
                cpe.setJavadocContainerUrl(apidocs.toURI().toURL());
            }
        });
        entries.add(cpe);
    }
    return ImmutableList.copyOf(entries);
}

From source file:org.switchyard.tools.ui.M2EUtils.java

License:Open Source License

/**
 * Returns the generated switchyard.xml file. By default, this is
 * target/class/META-INF/switchyard.xml.
 * //from  ww  w. jav  a 2s .  c o  m
 * @param project the project
 * @return the location of the generated switchyard.xml file.
 */
public static File getSwitchYardOutputFile(MavenProject project) {
    if (project == null) {
        return null;
    }
    Plugin plugin = findSwitchYardPlugin(project.getModel());
    if (plugin == null) {
        return null;
    }
    Xpp3Dom configuration = findSwitchYardPluginConfiguration(plugin);
    if (configuration != null) {
        Xpp3Dom node = configuration.getChild("outputFile"); //$NON-NLS-1$
        if (node != null && node.getValue() != null) {
            return new File(project.getBasedir(), node.getValue());
        }
        node = configuration.getChild("outputDirectory"); //$NON-NLS-1$
        if (node != null && node.getValue() != null) {
            return new File(new File(project.getBasedir(), node.getValue()), "META-INF/switchyard.xml"); //$NON-NLS-1$
        }
    }
    return new File(project.getBuild().getOutputDirectory(), "META-INF/switchyard.xml"); //$NON-NLS-1$
}

From source file:org.universAAL.maven.treebuilder.DependencyTreeBuilder.java

License:Apache License

/**
 * Resolves runtime dependencies of given artifact. It is assumed that
 * runtime dependencies are enclosed in a "uAAL-Runtime" maven profile.
 * Dependencies are resolved taking into account dependency management of
 * maven project which subtree is resolved. Thanks to that there is no need
 * to provide versions for runtime artifacts if they are managed in parent
 * poms.//  ww w  .  j  ava2 s.c o  m
 * 
 * 
 * @param nodeArtifact
 * @param managedVersions
 * @return
 */
private List getRuntimeDeps(final Artifact nodeArtifact, final ManagedVersionMap managedVersions,
        final List remoteRepositories) {
    try {
        List runtimeDeps = new ArrayList();
        Artifact pomArtifact = artifactFactory.createArtifact(nodeArtifact.getGroupId(),
                nodeArtifact.getArtifactId(), nodeArtifact.getVersion(), "", "pom");
        MavenProject pomProject = mavenProjectBuilder.buildFromRepository(pomArtifact, remoteRepositories,
                localRepository);
        List profiles = pomProject.getModel().getProfiles();
        if (profiles != null) {
            for (Object profileObj : profiles) {
                Profile profile = (Profile) profileObj;
                if (UAAL_RUNTIME_PROFILE.equals(profile.getId())) {
                    List deps = profile.getDependencies();
                    extractDepsFromProfile(deps, runtimeDeps, managedVersions);
                }
                if (this.includeTestRuntimes) {
                    if (this.stringifiedRoot.equals(FilteringVisitorSupport.stringify(nodeArtifact))) {
                        if (UAAL_TEST_RUNTIME_PROFILE.equals(profile.getId())) {
                            List deps = profile.getDependencies();
                            extractDepsFromProfile(deps, runtimeDeps, managedVersions);
                        }
                    }
                }
            }
        }
        return runtimeDeps;
    } catch (ProjectBuildingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.vaadin.directory.maven.DirectorySearchMojo.java

License:Apache License

protected static void directorySearch(MavenProject project, String searchFor, boolean add, boolean fullSearch) {
    List<Addon> list = Directory.search("7", searchFor, fullSearch);
    Model model = project.getModel();
    for (Addon a : list) {
        System.out.println(a.getName() + " - " + a.getSummary());
        if (a.getLicenses() != null) {
            for (License l : a.getLicenses()) {
                System.out.print("\tLicense: " + a.getLicenses().get(0).getName() + "\n");
            }//  www . j  a  v  a2  s. c  o m
        }

        System.out.println("\tRating: " + a.getAvgRating() + " / 5");
        if (a.getGroupId() == null || a.getArtifactId() == null) {
            System.out.print("\tMaven: n/a");
        } else {
            System.out.print("\tMaven: " + a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getVersion());
        }
        if (PomUtils.findDependency(model, a.getGroupId(), a.getArtifactId()) != null) {
            System.out.println(" (in pom.xml)");
        } else if (add && a.getArtifactId() != null && a.getGroupId() != null) {
            PomUtils.addDependency(model, a.getGroupId(), a.getArtifactId(), a.getVersion());
            System.out.println(" (added to pom.xml)");
        } else if (a.getArtifactId() != null && a.getGroupId() != null) {
            System.out.println(" (not present)");
        } else {
            System.out.println("");
        }
    }
}