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

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

Introduction

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

Prototype

File getFile();

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  a  v a2 s .  co  m*/
    }

    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) {// w w  w . j av  a  2  s.  com
        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:ar.com.fluxit.jqa.JQAMavenPlugin.java

License:Open Source License

private void doExecute(File buildDirectory, File outputDirectory, File testOutputDirectory,
        MavenProject project, File sourceDir, String sourceJavaVersion)
        throws IntrospectionException, TypeFormatException, FileNotFoundException, IOException,
        RulesContextFactoryException, ExporterException {
    // Add project dependencies to classpath
    getLog().debug("Adding project dependencies to classpath");
    final Collection<File> classPath = new ArrayList<File>();
    @SuppressWarnings("unchecked")
    final Set<Artifact> artifacts = project.getArtifacts();
    for (final Artifact artifact : artifacts) {
        classPath.add(artifact.getFile());
    }//ww  w .j  a v a 2 s .  com
    // Add project classes to classpath
    if (outputDirectory != null) {
        classPath.add(outputDirectory);
    }
    if (testOutputDirectory != null) {
        classPath.add(testOutputDirectory);
    }
    getLog().debug("Adding project classes to classpath");
    final Collection<File> classFiles = FileUtils.listFiles(buildDirectory,
            new SuffixFileFilter(RulesContextChecker.CLASS_SUFFIX), TrueFileFilter.INSTANCE);
    // Reads the config file
    getLog().debug("Reading rules context");
    final RulesContext rulesContext = RulesContextFactoryLocator.getRulesContextFactory()
            .getRulesContext(getRulesContextFile().getPath());
    getLog().debug("Checking rules for " + classFiles.size() + " files");
    final CheckingResult checkingResult = RulesContextChecker.INSTANCE.check(project.getArtifactId(),
            classFiles, classPath, rulesContext, new File[] { sourceDir }, sourceJavaVersion, getLogger());
    CheckingResultExporter.INSTANCE.export(checkingResult, project.getArtifactId(), getResultsDirectory(),
            this.xslt, getLogger());
}

From source file:ar.com.fluxit.jqa.JQASensor.java

License:Open Source License

@Override
public void analyse(Project project, SensorContext context) {
    try {//from   w w w. j  ava2 s .c o  m
        final RulesContext rulesContext = RulesContextLoader.INSTANCE.load();
        final File buildDirectory = project.getFileSystem().getBuildOutputDir();
        final Collection<File> classFiles = FileUtils.listFiles(buildDirectory,
                new SuffixFileFilter(RulesContextChecker.CLASS_SUFFIX), TrueFileFilter.INSTANCE);
        final Collection<File> classPath = new ArrayList<File>();
        @SuppressWarnings("unchecked")
        final Set<Artifact> artifacts = getProject().getArtifacts();
        for (final Artifact artifact : artifacts) {
            classPath.add(artifact.getFile());
        }
        // Add project classes to classpath
        if (project.getFileSystem().getBuildOutputDir() != null) {
            classPath.add(project.getFileSystem().getBuildOutputDir());
        }
        if (project.getFileSystem().getTestDirs() != null) {
            classPath.addAll(project.getFileSystem().getTestDirs());
        }
        final File sourcesDir = new File((String) getProject().getCompileSourceRoots().get(0));
        LOGGER.info("SourcesDir = " + sourcesDir.getPath());
        final CheckingResult check = RulesContextChecker.INSTANCE.check(getProject().getArtifactId(),
                classFiles, classPath, rulesContext, new File[] { sourcesDir },
                getSourceJavaVersion(getProject()), LOGGER);
        addViolations(context, check);
    } catch (final Exception e) {
        LOGGER.error("An error occurred", e);
        throw new IllegalStateException(e);
    }
}

From source file:au.com.alderaan.eclipselink.mojo.EclipselinkStaticWeaveMojo.java

License:Apache License

@SuppressWarnings({ "unchecked" })
private URL[] buildClassPath() throws MalformedURLException {
    List<URL> urls = new ArrayList<URL>();
    Set<Artifact> artifacts = (Set<Artifact>) project.getArtifacts();
    for (Artifact a : artifacts) {
        urls.add(a.getFile().toURI().toURL());
    }/*from ww  w  . j  a  va 2s  .  c  o  m*/
    return urls.toArray(new URL[urls.size()]);
}

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 {// w ww. j  a  va  2 s.  c  om
            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 byte[] readBytesForClassFromArtifact(String className, Artifact artifact) throws EnforcerRuleException {
    try {/*  w ww . j  a va2s. co m*/
        JarFile jar = new JarFile(artifact.getFile());
        try {
            for (JarEntry entry : Collections.<JarEntry>list(jar.entries())) {
                if (className.equals(entry.getName())) {
                    return convertInputStreamToByteArray(jar.getInputStream(entry));
                }
            }
            throw new RuntimeException(String.format("Expected to find %s in artifact: %s:%s:%s", className,
                    artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
        } finally {
            try {
                jar.close();
            } catch (IOException e) {
            }
        }
    } catch (IOException e) {
        throw new EnforcerRuleException("Unable to process dependency " + artifact.getFile().getAbsolutePath()
                + " due to " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.applet.maven.sql.ddl.SQLDDLMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("SQL DDL script generator");

    File outputFile = new File(this.outputDirectory, this.outputName);
    getLog().info("Output SQL DDL script file: " + outputFile.getAbsolutePath());

    this.outputDirectory.mkdirs();
    try {//from   w ww . j  av a  2 s .  c  o  m
        outputFile.createNewFile();
    } catch (IOException e) {
        throw new MojoExecutionException("I/O error.", e);
    }

    for (ArtifactItem artifactItem : this.artifactItems) {
        getLog().info("artifact: " + artifactItem.getGroupId() + ":" + artifactItem.getArtifactId());
        List<Dependency> dependencies = this.project.getDependencies();
        String version = null;
        for (Dependency dependency : dependencies) {
            if (StringUtils.equals(dependency.getArtifactId(), artifactItem.getArtifactId())
                    && StringUtils.equals(dependency.getGroupId(), artifactItem.getGroupId())) {
                version = dependency.getVersion();
                break;
            }
        }
        getLog().info("artifact version: " + version);
        VersionRange versionRange = VersionRange.createFromVersion(version);
        Artifact artifact = this.artifactFactory.createDependencyArtifact(artifactItem.getGroupId(),
                artifactItem.getArtifactId(), versionRange, "jar", null, Artifact.SCOPE_COMPILE);
        try {
            this.resolver.resolve(artifact, this.remoteRepos, this.local);
        } catch (ArtifactResolutionException e) {
            throw new MojoExecutionException("Unable to resolve artifact.", e);
        } catch (ArtifactNotFoundException e) {
            throw new MojoExecutionException("Unable to find artifact.", e);
        }
        getLog().info("artifact file: " + artifact.getFile().getAbsolutePath());
        getLog().info("hibernate dialect: " + this.hibernateDialect);

        URL artifactUrl;
        try {
            artifactUrl = artifact.getFile().toURI().toURL();
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("URL error.", e);
        }

        URLClassLoader classLoader = new URLClassLoader(new URL[] { artifactUrl },
                this.getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(classLoader);

        AnnotationDB annotationDb = new AnnotationDB();
        try {
            annotationDb.scanArchives(artifactUrl);
        } catch (IOException e) {
            throw new MojoExecutionException("I/O error.", e);
        }
        Set<String> classNames = annotationDb.getAnnotationIndex().get(Entity.class.getName());
        getLog().info("# JPA entity classes: " + classNames.size());

        AnnotationConfiguration configuration = new AnnotationConfiguration();

        configuration.setProperty("hibernate.dialect", this.hibernateDialect);
        Dialect dialect = Dialect.getDialect(configuration.getProperties());
        getLog().info("dialect: " + dialect.toString());

        for (String className : classNames) {
            getLog().info("JPA entity: " + className);
            Class<?> entityClass;
            try {
                entityClass = classLoader.loadClass(className);
                getLog().info("entity class loader: " + entityClass.getClassLoader());
            } catch (ClassNotFoundException e) {
                throw new MojoExecutionException("class not found.", e);
            }
            configuration.addAnnotatedClass(entityClass);
        }

        SchemaExport schemaExport = new SchemaExport(configuration);
        schemaExport.setFormat(true);
        schemaExport.setHaltOnError(true);
        schemaExport.setOutputFile(outputFile.getAbsolutePath());
        schemaExport.setDelimiter(";");

        try {
            getLog().info("SQL DDL script: " + IOUtil.toString(new FileInputStream(outputFile)));
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("file not found.", e);
        } catch (IOException e) {
            throw new MojoExecutionException("I/O error.", e);
        }

        // operate
        schemaExport.execute(true, false, false, true);
        List<Exception> exceptions = schemaExport.getExceptions();
        for (Exception exception : exceptions) {
            getLog().error("exception: " + exception.getMessage());
        }
    }
}

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

License:Open Source License

/**
 * Returns URLs whose represents artifacts.
 * @param artifacts the collection which stores artifacts.
 * @return the artifacts' URLs.//w  w  w .  jav a2 s.  c  o m
 * @since 1.4.0
 */
protected List<URL> resolveArtifactsUrls(final Collection<Artifact> artifacts) {
    final List<URL> urls = new ArrayList<URL>(artifacts.size());
    for (final Artifact artifact : artifacts) {
        try {
            urls.add(artifact.getFile().toURI().toURL());
        } catch (final MalformedURLException e) {
            // never
            throw new IllegalStateException(
                    String.format("Cannot add %s to the classpath!", createDisplayText(artifact)), e);
        }
    }
    return urls;
}

From source file:biz.paluch.maven.configurator.ConfigureArtifactMojo.java

License:Open Source License

/**
 * Perform configuration for an external artifact.
 *
 * @throws MojoExecutionException/* w w w. java2s. c o m*/
 * @throws MojoFailureException
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    Artifact artifact = factory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);

    try {
        artifactResolver.resolve(artifact, pomRemoteRepositories, localRepository);
    } catch (AbstractArtifactResolutionException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

    configure(artifact.getFile());
}