Example usage for org.apache.maven.artifact Artifact getType

List of usage examples for org.apache.maven.artifact Artifact getType

Introduction

In this page you can find the example usage for org.apache.maven.artifact Artifact getType.

Prototype

String getType();

Source Link

Usage

From source file:apparat.embedding.maven.AbstractApparatMojo.java

License:Open Source License

private void processArtifact(final Artifact artifact) throws MojoExecutionException, MojoFailureException {
    if (null == artifact) {
        return;/*from ww w.j av  a 2  s. com*/
    }

    final String artifactType = artifact.getType();
    if (artifactType.equals("swc") || artifactType.equals("swf")) {
        try {
            if (null != artifact.getFile()) {
                processFile(artifact.getFile());
            }
        } catch (final Throwable cause) {
            throw new MojoExecutionException("Apparat execution failed.", cause);
        }
    } else {
        getLog().debug("Skipped artifact since its type is " + artifactType + ".");
    }
}

From source file:aQute.bnd.maven.plugin.BndMavenPlugin.java

License:Open Source License

public void execute() throws MojoExecutionException {
    if (skip) {//from w w w.  j a v a2 s  .c  o m
        logger.debug("skip project as configured");
        return;
    }

    // Exit without generating anything if this is a pom-packaging project.
    // Probably it's just a parent project.
    if (PACKAGING_POM.equals(project.getPackaging())) {
        logger.info("skip project with packaging=pom");
        return;
    }

    Properties beanProperties = new BeanProperties();
    beanProperties.put("project", project);
    beanProperties.put("settings", settings);
    Properties mavenProperties = new Properties(beanProperties);
    mavenProperties.putAll(project.getProperties());

    try (Builder builder = new Builder(new Processor(mavenProperties, false))) {
        builder.setTrace(logger.isDebugEnabled());

        builder.setBase(project.getBasedir());
        propertiesFile = loadProjectProperties(builder, project);
        builder.setProperty("project.output", targetDir.getCanonicalPath());

        // If no bundle to be built, we have nothing to do
        if (Builder.isTrue(builder.getProperty(Constants.NOBUNDLES))) {
            logger.debug(Constants.NOBUNDLES + ": true");
            return;
        }

        // Reject sub-bundle projects
        List<Builder> subs = builder.getSubBuilders();
        if ((subs.size() != 1) || !builder.equals(subs.get(0))) {
            throw new MojoExecutionException("Sub-bundles not permitted in a maven build");
        }

        // Reject wab projects
        if (builder.getProperty(Constants.WAB) != null) {
            throw new MojoExecutionException(Constants.WAB + " not supported in a maven build");
        }
        if (builder.getProperty(Constants.WABLIB) != null) {
            throw new MojoExecutionException(Constants.WABLIB + " not supported in a maven build");
        }

        // Include local project packages automatically
        if (classesDir.isDirectory()) {
            Jar classesDirJar = new Jar(project.getName(), classesDir);
            classesDirJar.setManifest(new Manifest());
            builder.setJar(classesDirJar);
        }

        // Compute bnd classpath
        Set<Artifact> artifacts = project.getArtifacts();
        List<Object> buildpath = new ArrayList<Object>(artifacts.size());
        for (Artifact artifact : artifacts) {
            File cpe = artifact.getFile().getCanonicalFile();
            if (!cpe.exists()) {
                logger.debug("dependency {} does not exist", cpe);
                continue;
            }
            if (cpe.isDirectory()) {
                Jar cpeJar = new Jar(cpe);
                builder.addClose(cpeJar);
                builder.updateModified(cpeJar.lastModified(), cpe.getPath());
                buildpath.add(cpeJar);
            } else {
                if (!artifact.getType().equals("jar")) {
                    /*
                     * Check if it is a valid zip file. We don't create a
                     * Jar object here because we want to avoid the cost of
                     * creating the Jar object if we decide not to build.
                     */
                    try (ZipFile zip = new ZipFile(cpe)) {
                        zip.entries();
                    } catch (ZipException e) {
                        logger.debug("dependency {} is not a zip", cpe);
                        continue;
                    }
                }
                builder.updateModified(cpe.lastModified(), cpe.getPath());
                buildpath.add(cpe);
            }
        }
        builder.setProperty("project.buildpath", Strings.join(File.pathSeparator, buildpath));
        logger.debug("builder classpath: {}", builder.getProperty("project.buildpath"));

        // Compute bnd sourcepath
        boolean delta = !buildContext.isIncremental() || manifestOutOfDate();
        List<File> sourcepath = new ArrayList<File>();
        if (sourceDir.exists()) {
            sourcepath.add(sourceDir.getCanonicalFile());
            delta |= buildContext.hasDelta(sourceDir);
        }
        for (org.apache.maven.model.Resource resource : resources) {
            File resourceDir = new File(resource.getDirectory());
            if (resourceDir.exists()) {
                sourcepath.add(resourceDir.getCanonicalFile());
                delta |= buildContext.hasDelta(resourceDir);
            }
        }
        builder.setProperty("project.sourcepath", Strings.join(File.pathSeparator, sourcepath));
        logger.debug("builder sourcepath: {}", builder.getProperty("project.sourcepath"));

        // Set Bundle-SymbolicName
        if (builder.getProperty(Constants.BUNDLE_SYMBOLICNAME) == null) {
            builder.setProperty(Constants.BUNDLE_SYMBOLICNAME, project.getArtifactId());
        }
        // Set Bundle-Name
        if (builder.getProperty(Constants.BUNDLE_NAME) == null) {
            builder.setProperty(Constants.BUNDLE_NAME, project.getName());
        }
        // Set Bundle-Version
        if (builder.getProperty(Constants.BUNDLE_VERSION) == null) {
            Version version = MavenVersion.parseString(project.getVersion()).getOSGiVersion();
            builder.setProperty(Constants.BUNDLE_VERSION, version.toString());
            if (builder.getProperty(Constants.SNAPSHOT) == null) {
                builder.setProperty(Constants.SNAPSHOT, TSTAMP);
            }
        }

        logger.debug("builder properties: {}", builder.getProperties());
        logger.debug("builder delta: {}", delta);

        if (delta || (builder.getJar() == null) || (builder.lastModified() > builder.getJar().lastModified())) {
            // Set builder paths
            builder.setClasspath(buildpath);
            builder.setSourcepath(sourcepath.toArray(new File[0]));

            // Build bnd Jar (in memory)
            Jar bndJar = builder.build();

            // Expand Jar into target/classes
            expandJar(bndJar, classesDir);
        } else {
            logger.debug("No build");
        }

        // Finally, report
        reportErrorsAndWarnings(builder);
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException("bnd error: " + e.getMessage(), e);
    }
}

From source file:au.net.coldeq.enforcer.BanDuplicateClasses.java

License:Apache License

public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
    this.log = helper.getLog();
    MavenProject project = getMavenProject(helper);
    Set<Artifact> artifacts = project.getArtifacts();
    int numberOfArtifacts = artifacts.size();
    int numberProcessed = 0;
    Map<Artifact, Set<String>> artifactToClasses = new HashMap<Artifact, Set<String>>();
    for (Artifact artifact : artifacts) {
        HashSet<String> classesFoundInArtifact = new HashSet<String>();
        artifactToClasses.put(artifact, classesFoundInArtifact);

        File file = artifact.getFile();
        log.debug((numberProcessed + 1) + " / " + numberOfArtifacts + "\tSearching for duplicate classes in: "
                + file.getAbsolutePath());
        if (file == null) {
            log.info("OK, file is null. WTF! " + artifact.toString() + ". Ignoring...");
        } else if (!file.exists()) {
            log.info("OK, file does not exist. WTF! " + file.getAbsolutePath() + ". Ignoring...");
        } else if (file.isDirectory()) {
            log.info("File is a directory. why?" + file.getAbsolutePath() + ". Ignoring...");
        } else if (shouldIgnoreArtifactType(artifact)) {
            log.info("File is a..." + artifact.getType() + ": " + file.getAbsolutePath() + ". Ignoring...");
        } else {//from  w  w w .  ja  v  a 2 s . com
            classesFoundInArtifact.addAll(findClassesInJarFile(file));
        }
    }

    Map<String, Set<Artifact>> classesToArtifact = invert(artifactToClasses);
    Map<String, Set<Artifact>> duplicates = filterForClassesFoundInMoreThanOneArtifact(classesToArtifact);
    if (duplicates.isEmpty()) {
        log.info("No duplicates found");
    } else {
        assertThatAllDuplicatesAreOfClassesThatMatchToTheByte(duplicates);
    }
}

From source file:au.net.coldeq.enforcer.BanDuplicateClasses.java

License:Apache License

private boolean shouldIgnoreArtifactType(Artifact artifact) {
    return !ALLOWED_ARTIFACT_TYPES.contains(artifact.getType());
}

From source file:biz.gabrys.maven.plugin.util.classpath.ContextClassLoaderExtender.java

License:Open Source License

/**
 * Filters artifacts based on the type./*from w  ww  .j a  va  2 s. c  o m*/
 * @param artifacts the collection which stores artifacts.
 * @param types the supported types.
 * @return the list with artifacts whose types fit to the supported types.
 * @since 1.4.0
 */
protected List<Artifact> filterArtifacts(final Collection<Artifact> artifacts, final Collection<String> types) {
    final List<Artifact> filtered = new LinkedList<Artifact>();
    for (final Artifact artifact : artifacts) {
        if (types.contains(artifact.getType())) {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Include %s", createDisplayText(artifact)));
            }
            filtered.add(artifact);
        } else if (logger.isDebugEnabled()) {
            logger.debug(String.format("Exclude %s", createDisplayText(artifact)));
        }
    }
    return filtered;
}

From source file:biz.gabrys.maven.plugin.util.classpath.ContextClassLoaderExtender.java

License:Open Source License

/**
 * Creates a text representation of the {@link Artifact}.
 * @param artifact the artifact.//  w w  w .j a va 2  s. c  o m
 * @return the text representation of the {@link Artifact}.
 * @since 1.4.0
 */
protected String createDisplayText(final Artifact artifact) {
    return String.format("%s:%s-%s.%s (%s)", artifact.getGroupId(), artifact.getArtifactId(),
            artifact.getVersion(), artifact.getType(), artifact.getScope());
}

From source file:br.com.anteros.restdoc.maven.plugin.util.ResourceResolver.java

License:Apache License

@SuppressWarnings("unchecked")
private static List<String> resolveAndUnpack(final List<Artifact> artifacts, final SourceResolverConfig config,
        final List<String> validClassifiers, final boolean propagateErrors)
        throws ArtifactResolutionException, ArtifactNotFoundException {
    // NOTE: Since these are '-sources' and '-test-sources' artifacts, they won't actually 
    // resolve transitively...this is just used to aggregate resolution failures into a single 
    // exception.
    final Set<Artifact> artifactSet = new LinkedHashSet<Artifact>(artifacts);
    final Artifact pomArtifact = config.project().getArtifact();
    final ArtifactRepository localRepo = config.localRepository();
    final List<ArtifactRepository> remoteRepos = config.project().getRemoteArtifactRepositories();
    final ArtifactMetadataSource metadataSource = config.artifactMetadataSource();

    final ArtifactFilter filter = config.filter();
    ArtifactFilter resolutionFilter = null;
    if (filter != null) {
        // Wrap the filter in a ProjectArtifactFilter in order to always include the pomArtifact for resolution.
        // NOTE that this is necessary, b/c the -sources artifacts are added dynamically to the pomArtifact
        // and the resolver also checks the dependency trail with the given filter, thus the pomArtifact has
        // to be explicitly included by the filter, otherwise the -sources artifacts won't be resolved.
        resolutionFilter = new ProjectArtifactFilter(pomArtifact, filter);
    }//from  ww  w.ja va2  s .  com

    final ArtifactResolver resolver = config.artifactResolver();

    @SuppressWarnings("rawtypes")
    Map managed = config.project().getManagedVersionMap();

    final ArtifactResolutionResult resolutionResult = resolver.resolveTransitively(artifactSet, pomArtifact,
            managed, localRepo, remoteRepos, metadataSource, resolutionFilter);

    final List<String> result = new ArrayList<String>(artifacts.size());
    for (final Artifact a : (Collection<Artifact>) resolutionResult.getArtifacts()) {
        if (!validClassifiers.contains(a.getClassifier()) || (filter != null && !filter.include(a))) {
            continue;
        }

        final File d = new File(config.outputBasedir(),
                a.getArtifactId() + "-" + a.getVersion() + "-" + a.getClassifier());

        if (!d.exists()) {
            d.mkdirs();
        }

        try {
            final UnArchiver unArchiver = config.archiverManager().getUnArchiver(a.getType());

            unArchiver.setDestDirectory(d);
            unArchiver.setSourceFile(a.getFile());

            unArchiver.extract();

            result.add(d.getAbsolutePath());
        } catch (final NoSuchArchiverException e) {
            if (propagateErrors) {
                throw new ArtifactResolutionException(
                        "Failed to retrieve valid un-archiver component: " + a.getType(), a, e);
            }
        } catch (final ArchiverException e) {
            if (propagateErrors) {
                throw new ArtifactResolutionException("Failed to unpack: " + a.getId(), a, e);
            }
        }
    }

    return result;
}

From source file:br.com.uggeri.maven.builder.mojo.ArtifactUtil.java

public final static String artifactName(Artifact artifact) {
    StringBuilder sb = new StringBuilder();
    sb.append(artifact.getArtifactId()).append('-');
    if (artifact.getVersion().isEmpty()) {
        sb.append(artifact.getBaseVersion());
    } else {/*from  ww w  . j  a  va  2  s .c  om*/
        sb.append(artifact.getVersion());
    }
    if (artifact.hasClassifier()) {
        sb.append('-').append(artifact.getClassifier());
    }
    sb.append('.').append(artifact.getType());
    return sb.toString();
}

From source file:br.com.uggeri.maven.builder.mojo.ArtifactUtil.java

static boolean areEqual(Artifact a, Dependency d) {
    return a.getGroupId().equals(d.getGroupId()) && a.getArtifactId().equals(d.getArtifactId())
            && a.getVersion().equals(d.getVersion()) && a.getType().equals(d.getType())
            && ((a.getClassifier() == null && d.getClassifier() == null)
                    || a.getClassifier().equals(d.getClassifier()));
}

From source file:ch.ivyteam.ivy.maven.AbstractProjectCompileMojo.java

License:Apache License

protected final List<File> getDependencies(String type) {
    Set<org.apache.maven.artifact.Artifact> dependencies = project.getArtifacts();
    if (dependencies == null) {
        return Collections.emptyList();
    }/*  w  w w.  j  av  a2 s . com*/

    List<File> dependentIars = new ArrayList<>();
    for (org.apache.maven.artifact.Artifact artifact : dependencies) {
        if (artifact.getType().equals(type)) {
            dependentIars.add(artifact.getFile());
        }
    }
    return dependentIars;
}