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:com.jayway.maven.plugins.android.phase_prebuild.ClasspathModifierLifecycleParticipant.java

License:Open Source License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - start");
    log.debug("");

    log.debug("CurrentProject=" + session.getCurrentProject());
    final List<MavenProject> projects = session.getProjects();
    final DependencyResolver dependencyResolver = new DependencyResolver(log, dependencyGraphBuilder);
    final ArtifactResolverHelper artifactResolverHelper = new ArtifactResolverHelper(artifactResolver, log);

    for (MavenProject project : projects) {
        log.debug("");
        log.debug("project=" + project.getArtifact());

        if (!AndroidExtension.isAndroidPackaging(project.getPackaging())) {
            continue; // do not modify classpath if not an android project.
        }/*www . j ava  2 s.c o  m*/

        final UnpackedLibHelper helper = new UnpackedLibHelper(artifactResolverHelper, project, log);

        final Set<Artifact> artifacts;

        // If there is an extension ClassRealm loaded for this project then use that
        // as the ContextClassLoader so that Wagon extensions can be used to resolves dependencies.
        final ClassLoader projectClassLoader = (project.getClassRealm() != null) ? project.getClassRealm()
                : Thread.currentThread().getContextClassLoader();

        final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(projectClassLoader);
            artifacts = dependencyResolver.getProjectDependenciesFor(project, session);
        } catch (DependencyGraphBuilderException e) {
            // Nothing to do. The resolution failure will be displayed by the standard resolution mechanism.
            continue;
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }

        log.debug("projects deps: : " + artifacts);
        for (Artifact artifact : artifacts) {
            final String type = artifact.getType();
            if (type.equals(AndroidExtension.AAR)) {
                // An AAR lib contains a classes jar that needs to be added to the classpath.
                // Create a placeholder classes.jar and add it to the compile classpath.
                // It will replaced with the real classes.jar by GenerateSourcesMojo.
                addClassesToClasspath(helper, project, artifact);
                // Add jar files in 'libs' into classpath.
                addLibsJarsToClassPath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APK)) {
                // The only time that an APK will likely be a dependency is when this an an APK test project.
                // So add a placeholder (we cannot resolve the actual dep pre build) to the compile classpath.
                // The placeholder will be replaced with the real APK jar later.
                addClassesToClasspath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APKLIB)) {
                // Add jar files in 'libs' into classpath.
                addLibsJarsToClassPath(helper, project, artifact);
            }
        }
    }
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - finish");
}

From source file:com.liferay.ide.maven.core.MavenBundlePluginProject.java

License:Open Source License

@Override
public String getSymbolicName() throws CoreException {
    String bsn = ProjectUtil.getBundleSymbolicNameFromBND(getProject());

    if (!CoreUtil.empty(bsn)) {
        return bsn;
    }/*from  w w  w .j av a2 s .  c om*/

    String retval = null;

    final IProgressMonitor monitor = new NullProgressMonitor();
    final IMavenProjectFacade projectFacade = MavenUtil.getProjectFacade(getProject(), monitor);
    final MavenProject mavenProject = projectFacade.getMavenProject(monitor);

    final Artifact artifact = mavenProject.getArtifact();
    final File file = artifact.getFile();

    if (file != null && file.exists() && !artifact.getFile().getName().equals("classes")) {
        retval = new DefaultMaven2OsgiConverter().getBundleSymbolicName(artifact);
    } else {
        // fallback to project name
        retval = getProject().getLocation().lastSegment();
    }

    return retval;
}

From source file:com.mcleodmoores.mvn.natives.PackageMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().debug("Skipping step");
        return;/* w  ww .j  a  va  2s.c om*/
    }
    applyDefaults();
    final MavenProject project = (MavenProject) getPluginContext().get("project");
    final File targetDir = new File(project.getBuild().getDirectory());
    targetDir.mkdirs();
    final File targetFile = new File(targetDir, project.getArtifactId() + ".zip");
    getLog().debug("Writing to " + targetFile);
    final OutputStream output;
    try {
        output = getOutputStreams().open(targetFile);
    } catch (final IOException e) {
        throw new MojoFailureException("Can't write to " + targetFile);
    }
    final IOExceptionHandler errorLog = new MojoLoggingErrorCallback(this);
    if ((new IOCallback<OutputStream, Boolean>(output) {

        @Override
        protected Boolean apply(final OutputStream output) throws IOException {
            final byte[] buffer = new byte[4096];
            final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(output));
            for (final Map.Entry<Source, String> sourceInfo : gatherSources().entrySet()) {
                final Source source = sourceInfo.getKey();
                getLog().info("Processing " + source.getPath() + " into " + sourceInfo.getValue() + " ("
                        + source.getPattern() + ")");
                final File folder = new File(source.getPath());
                final String[] files = folder.list(new PatternFilenameFilter(regex(source.getPattern())));
                if (files != null) {
                    for (final String file : files) {
                        getLog().debug("Adding " + file + " to archive");
                        final ZipEntry entry = new ZipEntry(sourceInfo.getValue() + file);
                        zip.putNextEntry(entry);
                        if ((new IOCallback<InputStream, Boolean>(
                                getInputStreams().open(new File(folder, file))) {

                            @Override
                            protected Boolean apply(final InputStream input) throws IOException {
                                int bytes;
                                while ((bytes = input.read(buffer, 0, buffer.length)) > 0) {
                                    zip.write(buffer, 0, bytes);
                                }
                                return Boolean.TRUE;
                            }

                        }).call(errorLog) != Boolean.TRUE) {
                            return Boolean.FALSE;
                        }
                        zip.closeEntry();
                    }
                } else {
                    getLog().debug("Source folder is empty or does not exist");
                }
            }
            zip.close();
            return Boolean.TRUE;
        }

    }).call(errorLog) != Boolean.TRUE) {
        throw new MojoFailureException("Error writing to " + targetFile);
    }
    project.getArtifact().setFile(targetFile);
}

From source file:com.monday_consulting.maven.plugins.fsm.util.resolver.MavenGetArtifactsResolver.java

License:Apache License

private MavenProject getMavenProjectViaRepository(final Module module, final ProjectBuilder projectBuilder)
        throws MojoFailureException {
    try {/*  w  w w .  j a  v a 2s .  c  o  m*/
        final ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
        request.setResolveDependencies(true);
        request.setRemoteRepositories(mavenProject.getRemoteArtifactRepositories());
        request.setRepositorySession(repoSession);

        final LocalRepositoryManager localRepositoryManager = repoSession.getLocalRepositoryManager();
        final File repoBasedir = localRepositoryManager.getRepository().getBasedir();

        // the module type artifact (war, jar, pom ...)
        final DefaultArtifact moduleArtifact = new DefaultArtifact(module.getGroupId(), module.getArtifactId(),
                module.getClassifier(), module.getType(), module.getVersion());
        final String pathForLocalArtifact = localRepositoryManager.getPathForLocalArtifact(moduleArtifact);
        final File moduleArtifactFile = new File(repoBasedir, pathForLocalArtifact);

        // the module pom artifact to build maven project
        final DefaultArtifact pomArtifact = new DefaultArtifact(module.getGroupId(), module.getArtifactId(),
                module.getClassifier(), "pom", module.getVersion());
        final String localArtifactPath = localRepositoryManager.getPathForLocalArtifact(pomArtifact);

        final File projectFile = new File(repoBasedir, localArtifactPath);

        MavenProject result;
        try {
            log.info("try to build maven project for " + module.getArtifactId() + " from local repository...");
            result = projectBuilder.build(projectFile, request).getProject();

            if (!moduleArtifactFile.exists()) {
                resolveArtifact(module, moduleArtifact);
            }
        } catch (ProjectBuildingException e) {
            log.info("failed... try to resolve " + module.getArtifactId() + " from remote repository...");
            final Artifact mavenArtifact = new org.apache.maven.artifact.DefaultArtifact(module.getGroupId(),
                    module.getArtifactId(), module.getVersion(), null, module.getType(), module.getClassifier(),
                    new DefaultArtifactHandler());
            result = projectBuilder.build(mavenArtifact, request).getProject();

            resolveArtifact(module, moduleArtifact);
        }

        if (result != null) {
            log.info("Dependency resolved: " + module.getArtifactId());
            result.getArtifact().setFile(moduleArtifactFile);
            result.setParent(mavenProject);
        } else {
            throw new MojoFailureException(
                    "No dependency for " + module.getArtifactId() + " found in local or remote repository");
        }

        return result;
    } catch (ProjectBuildingException e) {
        throw new MojoFailureException(
                "No dependency for " + module.getArtifactId() + "found in local or remote repository", e);
    }
}

From source file:com.ning.maven.plugins.dependencyversionscheck.AbstractDependencyVersionsMojo.java

License:Apache License

/**
 * Returns a Set of artifacts based off the given project. Artifacts can be filtered and optional dependencies can be excluded.
 *
 * It would be awesome if this method would also use the DependencyTreeBuilder which seems to yield better results (and is much closer to the actual compile tree in some cases)
 * than the artifactResolver. However, due to MNG-3236 the artifact filter is not applied when resolving dependencies and this method relies on the artifact filter to get
 * the scoping right. Well, maybe in maven 3.0 this will be better. Or different. Whatever comes first.
 */// www .j  ava  2 s  .c  o m
private Set resolveDependenciesInItsOwnScope(final MavenProject project, final ArtifactFilter filter,
        final boolean includeOptional)
        throws InvalidDependencyVersionException, ArtifactResolutionException, ArtifactNotFoundException {
    Set dependencyArtifacts = MavenMetadataSource.createArtifacts(artifactFactory, project.getDependencies(),
            null, filter, null);

    ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts,
            project.getArtifact(), Collections.EMPTY_MAP, localRepository,
            project.getRemoteArtifactRepositories(), artifactMetadataSource,
            new ArtifactOptionalFilter(includeOptional));

    return result.getArtifacts();
}

From source file:com.puppetlabs.geppetto.forge.maven.plugin.Package.java

License:Open Source License

@Override
protected void invoke(Diagnostic result) throws Exception {
    Collection<File> moduleRoots = findModuleRoots();
    if (moduleRoots.isEmpty()) {
        result.addChild(new Diagnostic(ERROR, PACKAGE, "No modules found in repository"));
        return;//from  w  w w. j  a  va2s. co m
    }

    File buildDir = getBuildDir();
    buildDir.mkdirs();
    if (moduleRoots.size() == 1) {
        MavenProject project = getProject();
        File moduleRoot = moduleRoots.iterator().next();
        Metadata[] resultingMetadata = new Metadata[1];
        byte[][] resultingMD5 = new byte[1][];
        project.getArtifact()
                .setFile(buildForge(moduleRoot, buildDir, resultingMetadata, resultingMD5, result));

        Artifact pmriArtifact = repositorySystem.createArtifact(project.getGroupId(), project.getArtifactId(),
                project.getVersion(), "compile", "pmri");

        PuppetModuleReleaseInfo pmri = new PuppetModuleReleaseInfo();
        pmri.setMetadata(resultingMetadata[0]);
        pmri.populate(moduleRoot);

        File pmriFile = new File(buildDir, "release.pmri");
        OutputStream out = new FileOutputStream(pmriFile);
        try {
            Writer writer = new BufferedWriter(new OutputStreamWriter(out, Charsets.UTF_8));
            getGson().toJson(pmri, writer);
            writer.flush();
        } finally {
            out.close();
        }
        pmriArtifact.setFile(pmriFile);
        pmriArtifact.setResolved(true);
        project.addAttachedArtifact(pmriArtifact);
    } else {
        File builtModules = new File(buildDir, "builtModules");
        if (!(builtModules.mkdir() || builtModules.isDirectory())) {
            result.addChild(
                    new Diagnostic(ERROR, PACKAGE, "Unable to create directory" + builtModules.getPath()));
            return;
        }
        for (File moduleRoot : moduleRoots)
            buildForge(moduleRoot, builtModules, null, null, result);
    }
}

From source file:com.sap.prd.mobile.ios.mios.XCodePackageManager.java

License:Apache License

private void setMainArtifact(final MavenProject project, final File mainArtifactTarFile) {
    project.getArtifact().setFile(mainArtifactTarFile);
    LOGGER.info("Main artifact file '" + mainArtifactTarFile + "' attached for " + project.getArtifact());
}

From source file:com.sap.prd.mobile.ios.mios.XCodePackageManager.java

License:Apache License

static void attachLibrary(final XCodeContext xcodeContext, File buildDir, final MavenProject project,
        final MavenProjectHelper projectHelper) {

    final File fatBinary = XCodeBuildLayout.getBinary(buildDir, xcodeContext.getConfiguration(),
            xcodeContext.getSDK(), project.getArtifactId());

    if (!fatBinary.exists())
        throw new RuntimeException(fatBinary + " should be attached but does not exist.");

    final String classifier = xcodeContext.getConfiguration() + "-" + xcodeContext.getSDK();

    projectHelper.attachArtifact(project, "a", classifier, fatBinary);

    LOGGER.info("Archive file '" + fatBinary + "' attached as side artifact for '" + project.getArtifact()
            + "' with classifier '" + classifier + "'.");
}

From source file:com.secristfamily.maven.plugin.ZipMojo.java

/**
 * Retrieves all artifact dependencies.//from   ww w  .  jav a2 s  . c  o m
 * 
 * @return A HashSet of artifacts
 */
protected Set<Artifact> getDependencies() {
    MavenProject project = getProject();

    Set<Artifact> dependenciesSet = new HashSet<Artifact>();

    if (project.getArtifact() != null && project.getArtifact().getFile() != null)
        dependenciesSet.add(project.getArtifact());

    // As of version 1.5, project dependencies require runtime resolution:
    // see requiresDependencyResolution definition at top of class.
    Set projectArtifacts = project.getArtifacts();
    if (projectArtifacts != null)
        dependenciesSet.addAll(projectArtifacts);

    this.filterArtifacts(dependenciesSet);
    return dependenciesSet;
}

From source file:com.simpligility.maven.plugins.android.phase_prebuild.ClasspathModifierLifecycleParticipant.java

License:Open Source License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - start");
    log.debug("");

    log.debug("CurrentProject=" + session.getCurrentProject());
    final List<MavenProject> projects = session.getProjects();
    final DependencyResolver dependencyResolver = new DependencyResolver(log, dependencyGraphBuilder);
    final ArtifactResolverHelper artifactResolverHelper = new ArtifactResolverHelper(artifactResolver, log);

    for (MavenProject project : projects) {
        log.debug("");
        log.debug("project=" + project.getArtifact());

        if (!AndroidExtension.isAndroidPackaging(project.getPackaging())) {
            continue; // do not modify classpath if not an android project.
        }//ww  w .j  a v  a 2  s . com

        final String unpackedLibsFolder = getMojoConfigurationParameter(project, UNPACKED_LIBS_FOLDER_PARAM,
                null);
        final UnpackedLibHelper helper = new UnpackedLibHelper(artifactResolverHelper, project, log,
                unpackedLibsFolder == null ? null : new File(unpackedLibsFolder));

        final Set<Artifact> artifacts;

        // If there is an extension ClassRealm loaded for this project then use that
        // as the ContextClassLoader so that Wagon extensions can be used to resolves dependencies.
        final ClassLoader projectClassLoader = (project.getClassRealm() != null) ? project.getClassRealm()
                : Thread.currentThread().getContextClassLoader();

        final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(projectClassLoader);
            artifacts = dependencyResolver.getProjectDependenciesFor(project, session);
        } catch (DependencyGraphBuilderException e) {
            // Nothing to do. The resolution failure will be displayed by the standard resolution mechanism.
            continue;
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }

        boolean includeFromAar = getMojoConfigurationParameter(project, INCLUDE_FROM_AAR_PARAM,
                INCLUDE_FROM_AAR_DEFAULT);
        boolean includeFromApklib = getMojoConfigurationParameter(project, INCLUDE_FROM_APKLIB_PARAM,
                INCLUDE_FROM_APKLIB_DEFAULT);
        boolean disableConflictingDependenciesWarning = getMojoConfigurationParameter(project,
                DISABLE_CONFLICTING_DEPENDENCIES_WARNING_PARAM,
                DISABLE_CONFLICTING_DEPENDENCIES_WARNING_DEFAULT);

        log.debug("projects deps: : " + artifacts);

        if (!disableConflictingDependenciesWarning) {
            ProvidedDependencyChecker checker = new ProvidedDependencyChecker();
            checker.checkProvidedDependencies(artifacts, log);
        }

        for (Artifact artifact : artifacts) {
            final String type = artifact.getType();
            if (type.equals(AndroidExtension.AAR)) {
                // An AAR lib contains a classes jar that needs to be added to the classpath.
                // Create a placeholder classes.jar and add it to the compile classpath.
                // It will replaced with the real classes.jar by GenerateSourcesMojo.
                addClassesToClasspath(helper, project, artifact);

                // An AAR may also contain zero or more internal libs in the libs folder.
                // If 'includeLibsJarsFromAar' config param is true then include them too.
                if (includeFromAar) {
                    // Add jar files in 'libs' into classpath.
                    addLibsJarsToClassPath(helper, project, artifact);
                }
            } else if (type.equals(AndroidExtension.APK)) {
                // The only time that an APK will likely be a dependency is when this an an APK test project.
                // So add a placeholder (we cannot resolve the actual dep pre build) to the compile classpath.
                // The placeholder will be replaced with the real APK jar later.
                addClassesToClasspath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APKLIB)) {
                if (includeFromApklib) {
                    // Add jar files in 'libs' into classpath.
                    addLibsJarsToClassPath(helper, project, artifact);
                }
            }
        }
    }

    if (addedJarFromLibs) {
        log.warn("Transitive dependencies should really be provided by Maven dependency management.\n"
                + "          We suggest you to ask the above providers to package their component properly.\n"
                + "          Things may break at compile and/or runtime due to multiple copies of incompatible libraries.");
    }
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - finish");
}