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

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

Introduction

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

Prototype

public String getArtifactId() 

Source Link

Usage

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

License:Apache License

protected int execute(AFCliRequest cliRequest) throws MavenExecutionRequestPopulationException {
    MavenExecutionRequest request = reusableExecutionRequestPopulator.populateDefaults(cliRequest.getRequest());

    reusableEventSpyDispatcher.onEvent(request);

    MavenExecutionResult result = reusableMaven.execute(request);

    reusableEventSpyDispatcher.onEvent(result);

    reusableEventSpyDispatcher.close();/*from   ww  w. j  a  va2 s  .  co m*/

    if (result.hasExceptions()) {
        ExceptionHandler handler = new DefaultExceptionHandler();

        Map<String, String> references = new LinkedHashMap<String, String>();

        MavenProject project = null;

        for (Throwable exception : result.getExceptions()) {
            ExceptionSummary summary = handler.handleException(exception);

            logSummary(summary, references, "", cliRequest.isShowErrors());

            if (project == null && exception instanceof LifecycleExecutionException) {
                project = ((LifecycleExecutionException) exception).getProject();
            }
        }

        reusableSlf4jLogger.error("");

        if (!cliRequest.isShowErrors()) {
            reusableSlf4jLogger
                    .error("To see the full stack trace of the errors, re-run Maven with the -e switch.");
        }
        if (!reusableSlf4jLogger.isDebugEnabled()) {
            reusableSlf4jLogger.error("Re-run Maven using the -X switch to enable full debug logging.");
        }

        if (!references.isEmpty()) {
            reusableSlf4jLogger.error("");
            reusableSlf4jLogger.error("For more information about the errors and possible solutions"
                    + ", please read the following articles:");

            for (Entry<String, String> entry : references.entrySet()) {
                reusableSlf4jLogger.error(entry.getValue() + " " + entry.getKey());
            }
        }

        if (project != null && !project.equals(result.getTopologicallySortedProjects().get(0))) {
            reusableSlf4jLogger.error("");
            reusableSlf4jLogger
                    .error("After correcting the problems, you can resume the build with the command");
            reusableSlf4jLogger.error("  mvn <goals> -rf :" + project.getArtifactId());
        }

        if (MavenExecutionRequest.REACTOR_FAIL_NEVER
                .equals(cliRequest.getRequest().getReactorFailureBehavior())) {
            reusableSlf4jLogger.info("Build failures were ignored.");
            return 0;
        } else {
            return 1;
        }
    } else {
        return 0;
    }
}

From source file:org.kloeckner.maven.plugin.util.VersionRangeUtils.java

License:Apache License

public static String rewriteParent(MavenProject project, Element rootElement, Namespace namespace,
        Map<String, String> mappedVersions, Map<String, String> originalVersions)
        throws MojoExecutionException {
    String parentVersion = null;//  w  ww  . ja  v a  2  s . co m
    if (project.hasParent()) {
        Element parentElement = rootElement.getChild("parent", namespace);
        Element versionElement = parentElement.getChild("version", namespace);
        MavenProject parent = project.getParent();
        String key = ArtifactUtils.versionlessKey(parent.getGroupId(), parent.getArtifactId());
        parentVersion = mappedVersions.get(key);
        //         if (parentVersion == null) {
        //            //MRELEASE-317
        //            parentVersion = getResolvedSnapshotVersion(key, resolvedSnapshotDependencies);
        //         }
        if (parentVersion == null) {
            if (parent.getVersion().equals(originalVersions.get(key))) {
                throw new MojoExecutionException(
                        "Version for parent '" + parent.getName() + "' was not mapped");
            }
        } else {
            rewriteValue(versionElement, parentVersion);
        }
    }
    return parentVersion;
}

From source file:org.kuali.maven.plugins.externals.MojoHelper.java

License:Educational Community License

public GAV getGav(MavenProject project) {
    GAV gav = new GAV();
    gav.setGroupId(project.getGroupId());
    gav.setArtifactId(project.getArtifactId());
    gav.setVersion(project.getVersion());
    return gav;//from w w  w.  j  a v  a  2 s.c om
}

From source file:org.l2x6.maven.srcdeps.SrcdepsLifecycleParticipant.java

License:Apache License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    boolean globalSkip = Boolean
            .valueOf(session.getUserProperties().getProperty(Element.skip.toSrcDepsProperty(), "false"));
    if (globalSkip) {
        logger.info("srcdeps-maven-plugin skipped");
        return;//from   www  . j  av a 2s.  c o m
    }

    List<String> goals = session.getGoals();
    if (goals != null && shouldTriggerSrcdepsBuild(goals)) {
        List<MavenProject> projects = session.getProjects();
        logger.debug("SrcdepsLifecycleParticipant projects = " + projects);

        Set<Gav> projectGavs = new HashSet<SrcdepsLifecycleParticipant.Gav>();
        for (MavenProject project : projects) {
            projectGavs.add(Gav.ofModel(project.getModel()));
        }

        boolean builtSomething = false;

        for (MavenProject project : projects) {
            logger.info("srcdeps-maven-plugin scanning project " + project.getGroupId() + ":"
                    + project.getArtifactId());

            Optional<Plugin> plugin = findPlugin(project,
                    SrcdepsPluginConstants.ORG_L2X6_MAVEN_SRCDEPS_GROUP_ID,
                    SrcdepsPluginConstants.SRCDEPS_MAVEN_PLUGIN_ADRTIFACT_ID);
            if (plugin.isPresent() && project.getDependencies() != null) {

                Optional<Xpp3Dom> conf = plugin.map(Mapper.TO_DOM);
                if (conf.isPresent()) {

                    MojoExecution mojoExecution = new MojoExecution(plugin.value(), "install", "whatever");
                    PropsEvaluator evaluator = new PropsEvaluator(
                            new PluginParameterExpressionEvaluator(session, mojoExecution));
                    SrcdepsConfiguration srcdepsConfiguration = new SrcdepsConfiguration.Builder(evaluator,
                            conf.value(), session, logger).build();
                    if (srcdepsConfiguration.isSkip()) {
                        logger.info("srcdeps-maven-plugin skipped for project " + project.getGroupId() + ":"
                                + project.getArtifactId());
                    } else {
                        @SuppressWarnings("unchecked")
                        Map<Dependency, SrcVersion> revisions = filterSrcdeps(project.getDependencies(),
                                projectGavs);
                        if (!revisions.isEmpty()) {
                            assertFailWithProfiles(session, srcdepsConfiguration);
                            new SrcdepsInstaller(session, logger, artifactHandlerManager, srcdepsConfiguration,
                                    revisions, buildService).install();
                            builtSomething = true;
                        }
                    }
                }
            }
        }

        if (builtSomething) {
            Optional<Plugin> plugin = findPlugin(session.getTopLevelProject(), "org.apache.maven.plugins",
                    "maven-clean-plugin");
            if (plugin.isPresent()) {
                addCleanExclude(session.getTopLevelProject(), plugin.value());
            }
        }

    }
}

From source file:org.mobicents.maven.plugin.eclipse.ClasspathWriter.java

License:Open Source License

/**
 * Writes the .classpath file for eclipse.
 * /*www  . java2s .  c om*/
 * @param projects
 *            the list of projects from which the .classpath will get its
 *            dependencies.
 * @param repositoryVariableName
 *            the name of the maven repository variable.
 * @param artifactFactory
 *            the factory for constructing artifacts.
 * @param artifactResolver
 *            the artifact resolver.
 * @param localRepository
 *            the local repository instance.
 * @param artifactMetadataSource
 * @param classpathArtifactTypes
 *            the artifacts types that are allowed in the classpath file.
 * @param remoteRepositories
 *            the list of remote repository instances.
 * @param resolveTransitiveDependencies
 *            whether or not dependencies shall be transitively resolved.
 * @param merge
 *            anything extra (not auto-generated), that should be "merged"
 *            into the generated .classpath
 * @param classpathExcludes
 * @param includeTestsDirectory
 * @param includeResourcesDirectory
 * @throws Exception
 */
public void write(final List projects, final String repositoryVariableName,
        final ArtifactFactory artifactFactory, final ArtifactResolver artifactResolver,
        final ArtifactRepository localRepository, final ArtifactMetadataSource artifactMetadataSource,
        final Set classpathArtifactTypes, final List remoteRepositories,
        final boolean resolveTransitiveDependencies, final String merge, Set classpathExcludes,
        boolean includeResourcesDirectory) throws Exception {
    final String rootDirectory = PathNormalizer.normalizePath(this.project.getBasedir().toString());
    final File classpathFile = new File(rootDirectory, ".classpath");
    final FileWriter fileWriter = new FileWriter(classpathFile);
    final XMLWriter writer = new PrettyPrintXMLWriter(fileWriter, "UTF-8", null);
    writer.startElement("classpath");

    final Set projectArtifactIds = new LinkedHashSet();
    for (final Iterator iterator = projects.iterator(); iterator.hasNext();) {
        final MavenProject project = (MavenProject) iterator.next();
        final Artifact projectArtifact = artifactFactory.createArtifact(project.getGroupId(),
                project.getArtifactId(), project.getVersion(), null, project.getPackaging());
        projectArtifactIds.add(projectArtifact.getId());
    }

    // - collect the source roots for the root project (if they are any)
    Set<String> sourceRoots = collectSourceRoots(this.project, rootDirectory, writer,
            includeResourcesDirectory);

    final Set allArtifacts = new LinkedHashSet(this.project.createArtifacts(artifactFactory, null, null));

    for (final Iterator iterator = projects.iterator(); iterator.hasNext();) {
        final MavenProject project = (MavenProject) iterator.next();
        sourceRoots.addAll(collectSourceRoots(project, rootDirectory, writer, includeResourcesDirectory));
        final Set artifacts = project.createArtifacts(artifactFactory, null, null);
        // - get the direct dependencies
        for (final Iterator artifactIterator = artifacts.iterator(); artifactIterator.hasNext();) {
            final Artifact artifact = (Artifact) artifactIterator.next();
            // - don't attempt to resolve the artifact if its part of the
            // project (we
            // infer this if it has the same id has one of the projects or
            // is in
            // the same groupId).
            if (!projectArtifactIds.contains(artifact.getId())
                    && !project.getGroupId().equals(artifact.getGroupId())) {
                artifactResolver.resolve(artifact, project.getRemoteArtifactRepositories(), localRepository);
                allArtifacts.add(artifact);
            } else {
                allArtifacts.add(artifact);
            }
        }
    }

    // we have all source roots now, sort and write
    for (String sourceRoot : sourceRoots) {
        logger.info("Adding src path " + sourceRoot);
        this.writeClasspathEntry(writer, "src", sourceRoot);
    }

    // - remove the project artifacts
    for (final Iterator iterator = projects.iterator(); iterator.hasNext();) {
        final MavenProject project = (MavenProject) iterator.next();
        final Artifact projectArtifact = project.getArtifact();
        if (projectArtifact != null) {
            for (final Iterator artifactIterator = allArtifacts.iterator(); artifactIterator.hasNext();) {
                final Artifact artifact = (Artifact) artifactIterator.next();
                final String projectId = projectArtifact.getArtifactId();
                final String projectGroupId = projectArtifact.getGroupId();
                final String artifactId = artifact.getArtifactId();
                final String groupId = artifact.getGroupId();
                if (artifactId.equals(projectId) && groupId.equals(projectGroupId)) {
                    artifactIterator.remove();
                }
            }
        }
    }

    // - now we resolve transitively, if we have the flag on
    if (resolveTransitiveDependencies) {
        final Artifact rootProjectArtifact = artifactFactory.createArtifact(this.project.getGroupId(),
                this.project.getArtifactId(), this.project.getVersion(), null, this.project.getPackaging());

        final OrArtifactFilter filter = new OrArtifactFilter();
        filter.add(new ScopeArtifactFilter(Artifact.SCOPE_COMPILE));
        filter.add(new ScopeArtifactFilter(Artifact.SCOPE_PROVIDED));
        filter.add(new ScopeArtifactFilter(Artifact.SCOPE_TEST));
        final ArtifactResolutionResult result = artifactResolver.resolveTransitively(allArtifacts,
                rootProjectArtifact, localRepository, remoteRepositories, artifactMetadataSource, filter);

        allArtifacts.clear();
        allArtifacts.addAll(result.getArtifacts());
    }

    // remove excluded ones
    for (Iterator i = allArtifacts.iterator(); i.hasNext();) {
        Artifact artifact = (Artifact) i.next();

        if (classpathExcludes != null) {
            if (classpathExcludes.contains(artifact.getGroupId())) {
                logger.info("Excluding " + artifact + " from .classpath, groupId is excluded");
                i.remove();
            } else if (classpathExcludes.contains(artifact.getGroupId() + ":" + artifact.getArtifactId())) {
                logger.info("Excluding " + artifact + " from .classpath, groupId:artifactId is excluded");
                i.remove();
            } else if (classpathExcludes.contains(
                    artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion())) {
                logger.info(
                        "Excluding " + artifact + " from .classpath, groupId:artifactId:version is excluded");
                i.remove();
            }
        }
    }

    final List allArtifactPaths = new ArrayList(allArtifacts);
    for (final ListIterator iterator = allArtifactPaths.listIterator(); iterator.hasNext();) {
        final Artifact artifact = (Artifact) iterator.next();
        if (classpathArtifactTypes.contains(artifact.getType())) {
            File artifactFile = artifact.getFile();
            if (artifactFile == null) {
                artifactResolver.resolve(artifact, project.getRemoteArtifactRepositories(), localRepository);
                artifactFile = artifact.getFile();
            }
            if (artifactFile != null) {
                final String path = StringUtils.replace(PathNormalizer.normalizePath(artifactFile.toString()),
                        PathNormalizer.normalizePath(localRepository.getBasedir()), repositoryVariableName);
                iterator.set(path);
            } else {
                iterator.remove();
            }
        } else {
            iterator.remove();
        }
    }

    // - sort the paths
    Collections.sort(allArtifactPaths);

    for (final Iterator iterator = allArtifactPaths.iterator(); iterator.hasNext();) {
        String path = (String) iterator.next();
        if (path.startsWith(repositoryVariableName)) {
            this.writeClasspathEntry(writer, "var", path);
        } else {
            if (path.startsWith(rootDirectory)) {
                path = StringUtils.replace(path, rootDirectory + '/', "");
            }
            this.writeClasspathEntry(writer, "lib", path);
        }
    }

    this.writeClasspathEntry(writer, "con", "org.eclipse.jdt.launching.JRE_CONTAINER");

    String outputPath = StringUtils.replace(
            PathNormalizer.normalizePath(this.project.getBuild().getOutputDirectory()), rootDirectory, "");
    if (outputPath.startsWith("/")) {
        outputPath = outputPath.substring(1, outputPath.length());
    }
    this.writeClasspathEntry(writer, "output", outputPath);

    if (StringUtils.isNotBlank(merge)) {
        writer.writeMarkup(merge);
    }
    writer.endElement();

    logger.info("Classpath file written --> '" + classpathFile + "'");
    IOUtil.close(fileWriter);
}

From source file:org.mobicents.maven.plugin.EclipseMojo.java

License:Open Source License

/**
 * @see org.apache.maven.plugin.Mojo#execute()
 *//*www.  java  2s  . c  o  m*/
public void execute() throws MojoExecutionException

{
    if (!project.isExecutionRoot() && !generateProjectsForModules) {
        getLog().warn(
                "Skipping module because execution root project didn't configured generateProjectsForModules property as true");
        return;
    }
    try {
        final MavenProject rootProject = this.getRootProject();
        final ProjectWriter projectWriter = new ProjectWriter(rootProject, this.getLog());
        projectWriter.write(eclipseProjectName != null ? eclipseProjectName : project.getArtifactId());
        final Map originalCompileSourceRoots = this.collectProjectCompileSourceRoots();
        final List projects = this.collectProjects();
        this.processCompileSourceRoots(projects);
        final ClasspathWriter classpathWriter = new ClasspathWriter(rootProject, this.getLog());
        //TODO refactor to pass all arguments as an Options class or this will keep increasing the method signature
        classpathWriter.write(projects, this.repositoryVariableName, this.artifactFactory,
                this.artifactResolver, this.localRepository, this.artifactMetadataSource,
                this.classpathArtifactTypes, this.project.getRemoteArtifactRepositories(),
                this.resolveTransitiveDependencies, this.classpathMerge, this.classpathExcludes,
                this.includeResourcesDirectory);
        // - reset to the original source roots
        for (final Iterator iterator = projects.iterator(); iterator.hasNext();) {
            final MavenProject project = (MavenProject) iterator.next();
            project.getCompileSourceRoots().clear();
            project.getCompileSourceRoots().addAll((List) originalCompileSourceRoots.get(project));
        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        throw new MojoExecutionException("Error creating eclipse configuration", throwable);
    }

}

From source file:org.neo4j.build.plugins.ease.EaseHelper.java

License:Apache License

static void writeAndAttachArtifactList(StringBuilder builder, MavenProject project,
        MavenProjectHelper projectHelper, Log log) throws MojoExecutionException {
    String buildDir = project.getBuild().getDirectory();
    String destFile = buildDir + File.separator + project.getArtifactId() + "-" + project.getVersion()
            + "-artifacts.txt";
    try {/*from w  ww .j  a  v a2 s .c o m*/
        if (FileUtils.fileExists(destFile)) {
            FileUtils.fileDelete(destFile);
        }
        if (!FileUtils.fileExists(buildDir)) {
            FileUtils.mkdir(buildDir);
        }
        FileUtils.fileWrite(destFile, "UTF-8", builder.toString());
    } catch (IOException ioe) {
        throw new MojoExecutionException("Could not write artifact list.", ioe);
    }
    projectHelper.attachArtifact(project, "txt", "artifacts", FileUtils.getFile(destFile));
    log.info("Successfully attached artifact list to the project.");
}

From source file:org.objectstyle.woproject.maven2.javamonitor.JavaMonitorDeployMojo.java

License:Open Source License

/**
 * Generates the site structure using the project hiearchy (project and its
 * modules) or using the distributionManagement elements from the pom.xml.
 *
 * @param project//from   w w w. j  av  a  2 s  .  c  o  m
 * @param ignoreMissingSiteUrl
 * @return the structure relative path
 * @throws MojoFailureException
 *             if any
 */
protected static String getStructure(MavenProject project, boolean ignoreMissingSiteUrl)
        throws MojoFailureException {
    if (project.getDistributionManagement() == null) {
        String hierarchy = project.getArtifactId();

        MavenProject parent = project.getParent();
        while (parent != null) {
            hierarchy = parent.getArtifactId() + "/" + hierarchy;
            parent = parent.getParent();
        }

        return hierarchy;
    }

    Site site = project.getDistributionManagement().getSite();
    if (site == null) {
        if (!ignoreMissingSiteUrl) {
            throw new MojoFailureException(
                    "Missing site information in the distribution management element in the project: '"
                            + project.getName() + "'.");
        }

        return null;
    }

    if (StringUtils.isEmpty(site.getUrl())) {
        if (!ignoreMissingSiteUrl) {
            throw new MojoFailureException("The URL in the site is missing in the project descriptor.");
        }

        return null;
    }

    Repository repository = new Repository(site.getId(), site.getUrl());
    StringBuffer hierarchy = new StringBuffer(1024);
    hierarchy.append(repository.getHost());
    if (!StringUtils.isEmpty(repository.getBasedir())) {
        if (!repository.getBasedir().startsWith("/")) {
            hierarchy.append('/');
        }
        hierarchy.append(repository.getBasedir());
    }

    return hierarchy.toString().replaceAll("[\\:\\?\\*]", "");
}

From source file:org.openmrs.maven.plugins.bintray.OpenmrsBintray.java

public BintrayPackage createPackage(MavenProject mavenProject, String repository) {
    CreatePackageRequest request = new CreatePackageRequest();
    request.setName(mavenProject.getArtifactId());
    request.setDescription(mavenProject.getDescription());

    String githubUrl = mavenProject.getScm().getUrl();
    if (githubUrl.endsWith("/"))
        githubUrl = StringUtils.stripEnd(githubUrl, "/");
    String githubRepo = githubUrl.substring(githubUrl.lastIndexOf("/")).replace(".git", "");
    request.setVcsUrl(githubUrl + (githubUrl.endsWith(".git") ? "" : ".git"));
    request.setGithubRepo(OPENMRS_USERNAME + githubRepo);
    request.setWebsiteUrl("http://openmrs.org/");

    request.setIssueTrackerUrl(new DefaultJira().getJiraUrl());
    //so far all OpenMRS projects have MPL-2.0 license
    request.setLicenses(Arrays.asList("MPL-2.0"));
    return createPackage(OPENMRS_USERNAME, repository, request);
}

From source file:org.opennms.maven.plugins.tgz.AbstractAssemblyMojo.java

License:Apache License

private String getOutputDirectory(String output, MavenProject project, boolean includeBaseDirectory) {
    String value = output;/*from ww  w  . j  a  v a2s .  c  o m*/
    if (value == null) {
        value = "";
    }
    if (!value.endsWith("/") && !value.endsWith("\\")) {
        // TODO: shouldn't archiver do this?
        value += '/';
    }

    if (includeBaseDirectory) {
        if (value.startsWith("/")) {
            value = finalName + value;
        } else {
            value = finalName + "/" + value;
        }
    } else {
        if (value.startsWith("/")) {
            value = value.substring(1);
        }
    }

    if (project != null) {
        value = StringUtils.replace(value, "${groupId}", project.getGroupId());
        value = StringUtils.replace(value, "${artifactId}", project.getArtifactId());
        value = StringUtils.replace(value, "${version}", project.getVersion());

        Build build = project.getBuild();
        value = StringUtils.replace(value, "${build.finalName}", build.getFinalName());
        value = StringUtils.replace(value, "${finalName}", build.getFinalName());
    }

    return value;
}