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

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

Introduction

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

Prototype

public Artifact getArtifact() 

Source Link

Usage

From source file:net.java.jpatch.maven.ReleaseMojo.java

License:Apache License

/**
 * Creates the release package./*from   w ww. ja  v a2 s  .  co  m*/
 * 
 * @throws MojoExecutionException if the method fails.
 * @throws MojoFailureException if the method fails.
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    // Search for existing release
    Artifact releaseArtifact = resolveReleaseArtifact();
    File releaseFile = releaseArtifact.getFile();

    // Check existing release
    if (releaseFile != null && releaseFile.exists()) {
        getLog().info(releaseFile.getAbsolutePath());
        getLog().error("Release file already exist! For new release execute first jpatch:release-clean.");
        throw new MojoFailureException("Release package already exist!");
    }

    // Create release directory
    File directory = createTargetDirectory(releaseArtifact.getVersion());

    // Create release properties file.
    Properties releaseProperties = new Properties();

    // Load projects
    List<MavenProject> mavenProjects = loadMavenProjects();

    // Filter the projects
    List<MavenProject> filterProjects = filterMavenProjects(mavenProjects, getPackages());

    // Unpack the libraries in the output directory
    for (MavenProject project : filterProjects) {

        String revision = scmRevision(project);
        releaseProperties.setProperty(project.getId(), revision);

        Artifact artifact = project.getArtifact();
        resolveArtifactFromLocalRepository(artifact);
        unpackArtifactFile(directory, artifact.getFile());
    }

    // Setup the advanced properties to the release property
    SimpleDateFormat sdf = new SimpleDateFormat();
    releaseProperties.put(RELEASE_PROPERTY_DATE, sdf.format(new Date()));
    releaseProperties.put(RELEASE_PROPERTY_USER_NAME, SystemUtils.USER_NAME);
    releaseProperties.put(RELEASE_PROPERTY_JAVA_VERSION, SystemUtils.JAVA_VERSION);
    releaseProperties.put(RELEASE_PROPERTY_OS_NAME, SystemUtils.OS_NAME);

    // Save release properties file
    try {
        File propFile = new File(mavenProject.getBuild().getDirectory(),
                mavenProject.getBuild().getFinalName() + ".properties");
        releaseProperties.store(new FileOutputStream(propFile), null);
    } catch (IOException e) {
        throw new MojoExecutionException("Error creating the release properties file!", e);
    }

    // Create package file
    String fileName = mavenProject.getBuild().getFinalName();
    File packFile = new File(mavenProject.getBuild().getDirectory(), fileName + ".zip");
    packDirectory(directory, packFile);

    // Attached the package to the project
    releaseArtifact.setFile(packFile);
    mavenProject.addAttachedArtifact(releaseArtifact);

    // Create build file (project.jpatch)
    createBuildFile();
}

From source file:net.oneandone.maven.plugins.billofmaterials.CreateBillOfMaterialsMojo.java

License:Apache License

/**
 * Creates a list of all artifacts for the build.
 * @return a list of all artifacts for the build including the attached ones.
 *///w w  w  . j  a va  2s  .c  om
final List<File> getListOfArtifactsAsFiles() {
    final MavenProject project = getProject();
    final List<Artifact> attachedArtifacts = project.getAttachedArtifacts();
    // We need a copy here as otherwise install and deploy will choke later on because
    // we attach the POM as well.
    final List<File> files = new ArrayList<>(
            Collections2.filter(Lists.transform(attachedArtifacts, toFileFunction), Files.isFile()));
    final String packaging = project.getPackaging();
    // POMs return null as their artifact, which will crash the transformation lateron.
    if (!"pom".equals(packaging)) {
        files.add(project.getArtifact().getFile());
    }
    return files;
}

From source file:net.oneandone.maven.plugins.prerelease.core.Prerelease.java

License:Apache License

public void artifactFiles(MavenProject project, MavenProjectHelper projectHelper) throws IOException {
    FileNode file;//from  w ww.j  a va  2s  .  c o m
    String type;
    String classifier;
    String[] tmp;

    for (Map.Entry<FileNode, String[]> entry : artifactFiles().entrySet()) {
        file = entry.getKey();
        tmp = entry.getValue();
        classifier = tmp[0];
        type = tmp[1];
        if ("pom".equals(type) && !project.getPackaging().equals("pom")) {
            // ignored
        } else {
            if (classifier == null) {
                project.getArtifact().setFile(file.toPath().toFile());
            } else {
                projectHelper.attachArtifact(project, type, classifier, file.toPath().toFile());
            }
        }
    }
}

From source file:net.oneandone.maven.plugins.prerelease.util.PromoteExecutionListener.java

License:Apache License

@Override
public void projectStarted(ExecutionEvent event) {
    MavenProject project;
    Artifact projectArtifact;/*from  w ww  .j  av  a  2s .com*/
    Versioning versioning;
    ArtifactRepositoryMetadata metadata;
    GroupRepositoryMetadata groupMetadata;

    project = event.getSession().getCurrentProject();
    try {
        prerelease.artifactFiles(project, projectHelper);
        project.getProperties().putAll(prerelease.descriptor.deployProperties);
        if (prerelease.descriptor.deployPluginMetadata) {
            // from http://svn.apache.org/viewvc/maven/plugin-tools/tags/maven-plugin-tools-3.2/maven-plugin-plugin/src/main/java/org/apache/maven/plugin/plugin/metadata/AddPluginArtifactMetadataMojo.java

            projectArtifact = project.getArtifact();
            versioning = new Versioning();
            versioning.setLatest(projectArtifact.getVersion());
            versioning.updateTimestamp();
            metadata = new ArtifactRepositoryMetadata(projectArtifact, versioning);
            projectArtifact.addMetadata(metadata);
            groupMetadata = new GroupRepositoryMetadata(project.getGroupId());
            groupMetadata.addPluginMapping(
                    PluginDescriptor.getGoalPrefixFromArtifactId(project.getArtifactId()),
                    project.getArtifactId(), project.getName());

            projectArtifact.addMetadata(groupMetadata);
        }
    } catch (IOException e) {
        throw new RuntimeException("TODO", e);
    }
    super.projectStarted(event);
}

From source file:net.oneandone.maven.rules.ForbidDependencyManagementInSubModulesRule.java

License:Apache License

private void checkForSubmoduleDependencyManagement(final MavenProject project, Log log) {
    if (projectHasManagedDependencies(project) && !ruleIsDefinedInProjectOrNotModuleParent(project, log)
            && !isExcluded(RuleHelper.getProjectIdentifier(project))) {

        final DependencyManagement dependencyManagement = project.getOriginalModel().getDependencyManagement();
        if (dependencyManagement.getDependencies().size() > 0) {
            failureDetected = true;/*from  w  ww. j  a va2 s.c o  m*/
            logHeader(log, "dependency management in sub modules");
            for (Dependency dependency : dependencyManagement.getDependencies()) {
                log.warn("module '" + project.getArtifact().getDependencyConflictId()
                        + "' has dependency management for: " + dependency.getManagementKey());
            }
        }
    }
}

From source file:net.sf.buildbox.maven.contentcheck.LicenseShowMojo.java

License:Open Source License

private List<MavenProject> getMavenProjectForDependencies()
        throws MojoExecutionException, MojoFailureException {
    DependencyNode dependencyTreeNode = resolveProject();
    MavenProject project = getMavenProject();
    Dependencies dependencies = new Dependencies(project, dependencyTreeNode, classesAnalyzer);
    Log log = getLog();/*from www  .  j av  a 2s. c  o m*/
    RepositoryUtils repoUtils = new RepositoryUtils(log, wagonManager, settings, mavenProjectBuilder, factory,
            resolver, project.getRemoteArtifactRepositories(), project.getPluginArtifactRepositories(),
            localRepository, repositoryMetadataManager);
    Artifact projectArtifact = project.getArtifact();
    log.info(String.format("Resolving project %s:%s:%s dependencies", projectArtifact.getGroupId(),
            projectArtifact.getArtifactId(), projectArtifact.getVersion()));
    List<Artifact> allDependencies = dependencies.getAllDependencies();
    List<MavenProject> mavenProjects = new ArrayList<MavenProject>();
    for (Artifact artifact : allDependencies) {
        log.debug(String.format("Resolving project information for %s:%s:%s", artifact.getGroupId(),
                artifact.getArtifactId(), artifact.getVersion()));
        try {
            MavenProject mavenProject = repoUtils.getMavenProjectFromRepository(artifact);
            mavenProjects.add(mavenProject);
        } catch (ProjectBuildingException e) {
            throw new MojoFailureException(
                    String.format("Cannot get project information for artifact %s:%s:%s from repository",
                            artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()),
                    e);
        }
    }
    return mavenProjects;
}

From source file:net.sf.maven.plugin.autotools.CompileMojo.java

License:Apache License

@SuppressWarnings("unchecked")
//TODO fix this with modern resolution code
private Artifact resolveDependency(ArtifactDependency dependency)
        throws ArtifactResolutionException, ArtifactNotFoundException {
    MavenProject parent = mavenProject.getParent();
    if (parent != null) {
        List<MavenProject> sisters = parent.getCollectedProjects();
        if (sisters != null) {
            for (MavenProject sister : sisters) {
                Artifact artifact = sister.getArtifact();
                if (artifact != null) {
                    return artifact;
                }//from  w ww  .  j  av  a2 s  .c  om
            }
        }
    }
    Artifact artifact = artifactFactory.createArtifact(dependency.getGroupId(), dependency.getArtifactId(),
            dependency.getVersion(), null, "jar");
    resolver.resolve(artifact, remoteRepositories, localRepository);
    return artifact;
}

From source file:net.ubos.tools.pacmanpkgmavenplugin.PacmanPkgMavenPlugin.java

License:Open Source License

/**
 * {@inheritDoc}//w w  w  . j  a  v a2s  .com
 * 
 * @throws MojoExecutionException
 */
@Override
public void execute() throws MojoExecutionException {
    MavenProject project = (MavenProject) getPluginContext().get("project");
    String packaging = project.getPackaging();

    if (!"jar".equals(packaging) && !"ear".equals(packaging) && !"war".equals(packaging)) {
        return;
    }

    getLog().info("Generating PKGBUILD @ " + project.getName());

    // pull stuff out of MavenProject
    String artifactId = project.getArtifactId();
    String version = project.getVersion();
    String url = project.getUrl();
    String description = project.getDescription();
    Set<Artifact> dependencies = project.getDependencyArtifacts();
    File artifactFile = project.getArtifact().getFile();

    if (artifactFile == null || !artifactFile.exists()) {
        throw new MojoExecutionException("pacmanpkg must be executed as part of a build, not standalone,"
                + " otherwise it can't find the main JAR file");
    }
    // translate to PKGBUILD fields
    String pkgname = artifactId;
    String pkgver = version.replaceAll("-SNAPSHOT", "a"); // alpha
    String pkgdesc = "A Java package available on UBOS";
    if (description != null) {
        if (description.length() > 64) {
            pkgdesc = description.substring(0, 64) + "...";
        } else {
            pkgdesc = description;
        }
    }

    ArrayList<String> depends = new ArrayList<>(dependencies.size());
    for (Artifact a : dependencies) {
        if (!"test".equals(a.getScope())) {
            depends.add(a.getArtifactId());
        }
    }
    // write to PKGBUILD
    try {
        File baseDir = project.getBasedir();
        File pkgBuild = new File(baseDir, "target/PKGBUILD");
        PrintWriter out = new PrintWriter(pkgBuild);

        getLog().debug("Writing PKGBUILD to " + pkgBuild.getAbsolutePath());

        out.println("#");
        out.println(" * Automatically generated by pacman-pkg-maven-plugin; do not modify.");
        out.println("#");

        out.println();

        out.println("pkgname=" + pkgname);
        out.println("pkgver=" + pkgver);
        out.println("pkgrel=" + pkgrel);
        out.println("pkgdesc='" + pkgdesc + "'");
        out.println("arch=('any')");
        out.println("url='" + url + "'");
        out.println("license=('" + license + "')");

        out.print("depends=(");
        String sep = "";
        for (String d : depends) {
            out.print(sep);
            sep = ",";
            out.print("'");
            out.print(d);
            out.print("'");
        }
        out.println(")");

        out.println();

        out.println("package() (");
        out.println("   mkdir -p ${pkgdir}/usr/share/java");
        out.println("   install -m644 ${startdir}/" + artifactFile.getName() + " ${pkgdir}/usr/share/java/");
        out.println(")");

        out.close();

    } catch (IOException ex) {
        throw new MojoExecutionException("Failed to write target/PKGBUILD", ex);
    }
}

From source file:npanday.executable.impl.NetPluginExecutableFactoryImpl.java

License:Apache License

public NetExecutable getPluginRunner(MavenProject project, Artifact pluginArtifact,
        Set<Artifact> additionalDependencies, VendorRequirement vendorRequirement,
        ArtifactRepository localRepository, List<String> commands, File targetDir, String npandayVersion) throws

PlatformUnsupportedException, ArtifactResolutionException, ArtifactNotFoundException {

    Set dependencies = Sets.newHashSet(pluginArtifact);
    if (additionalDependencies != null) {
        dependencies.addAll(additionalDependencies);
    }//from   w w  w  .  j  a v a  2s  .co m

    // need to resolve what we can here since we need the path!
    Set<Artifact> artifacts = makeAvailable(project.getArtifact(), project.getManagedVersionMap(), dependencies,
            targetDir, localRepository,
            // TODO: consider, if this must be getRemotePluginRepositories()!!
            project.getRemoteArtifactRepositories());

    commands.add("startProcessAssembly=" + pluginArtifact.getFile().getAbsolutePath());

    String pluginArtifactPath = findArtifact(artifacts, "NPanday.Plugin").getFile().getAbsolutePath();
    commands.add("pluginArtifactPath=" + pluginArtifactPath);

    return getArtifactExecutable(project, createPluginRunnerArtifact(npandayVersion), dependencies,
            vendorRequirement, localRepository, commands, targetDir);
}

From source file:npanday.executable.impl.NetPluginExecutableFactoryImpl.java

License:Apache License

public NetExecutable getArtifactExecutable(MavenProject project, Artifact executableArtifact,
        Set<Artifact> additionalDependencies, VendorRequirement vendorRequirement,
        ArtifactRepository localRepository, List<String> commands, File targetDir) throws

PlatformUnsupportedException, ArtifactResolutionException, ArtifactNotFoundException {
    Set dependencies = Sets.newHashSet(executableArtifact);
    if (additionalDependencies != null) {
        dependencies.addAll(additionalDependencies);
    }/*from   w  w  w.  j  a v  a2  s  .c  om*/

    makeAvailable(project.getArtifact(), project.getManagedVersionMap(), dependencies, targetDir,
            localRepository,
            // TODO: consider, if this must be getRemotePluginRepositories()!!
            project.getRemoteArtifactRepositories());

    File artifactPath = executableArtifact.getFile();

    if (commands == null) {
        commands = new ArrayList<String>();
    }

    // TODO: this should be a separate implementation of NetExecutable, configured only for MONO!!!

    VendorInfo vendorInfo;
    try {
        vendorInfo = processor.process(vendorRequirement);
    } catch (IllegalStateException e) {
        throw new PlatformUnsupportedException(
                "NPANDAY-066-010: Illegal State: Vendor Info = " + vendorRequirement, e);
    }

    if (vendorInfo.getVendor() == null || vendorInfo.getFrameworkVersion() == null) {
        throw new PlatformUnsupportedException("NPANDAY-066-020: Missing Vendor Information: " + vendorInfo);
    }
    getLogger().debug("NPANDAY-066-003: Found Vendor: " + vendorInfo);

    List<String> modifiedCommands = new ArrayList<String>();
    String exe = null;

    if (vendorInfo.getVendor().equals(Vendor.MONO)) {
        List<File> executablePaths = vendorInfo.getExecutablePaths();
        if (executablePaths != null) {
            for (File executablePath : executablePaths) {
                if (new File(executablePath.getAbsolutePath(), "mono.exe").exists()) {
                    exe = new File(executablePath.getAbsolutePath(), "mono.exe").getAbsolutePath();
                    commands.add("vendor=MONO");//if forked process, it needs to know.
                    break;
                }
            }
        }

        if (exe == null) {
            getLogger().info(
                    "NPANDAY-066-005: Executable path for mono does not exist. Will attempt to execute MONO using"
                            + " the main PATH variable.");
            exe = "mono";
            commands.add("vendor=MONO");//if forked process, it needs to know.
        }
        modifiedCommands.add(artifactPath.getAbsolutePath());
        for (String command : commands) {
            modifiedCommands.add(command);
        }
    } else {
        exe = artifactPath.getAbsolutePath();
        modifiedCommands = commands;
    }
    //TODO: DotGNU on Linux?
    ExecutableConfig executableConfig = new ExecutableConfig();
    executableConfig.setExecutionPaths(Arrays.asList(exe));
    executableConfig.setCommands(modifiedCommands);

    try {
        repositoryExecutableContext.init(executableConfig);
    } catch (InitializationException e) {
        throw new PlatformUnsupportedException(
                "NPANDAY-066-006: Unable to initialize the repository executable context", e);
    }

    try {
        return repositoryExecutableContext.getNetExecutable();
    } catch (ExecutionException e) {
        throw new PlatformUnsupportedException("NPANDAY-066-004: Unable to find net executable", e);
    }
}