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

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

Introduction

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

Prototype

void setArtifactHandler(ArtifactHandler handler);

Source Link

Usage

From source file:com.redhat.tools.nexus.maven.plugin.buildhelper.InjectArtifactHandlerMojo.java

License:Open Source License

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
    ArtifactVersion currentVersion = ri.getApplicationVersion();
    ArtifactVersion maxUsageVersion = new DefaultArtifactVersion("2.2.0");

    if (maxUsageVersion.compareTo(currentVersion) < 0) {
        getLog().debug(/* ww  w.j av  a 2  s . c  o m*/
                "This version of Maven does not require injection of custom ArtifactHandlers using this code. Skipping.");
        return;
    }

    Map<String, ?> handlerDescriptors = session.getContainer().getComponentDescriptorMap(ArtifactHandler.ROLE);
    if (handlerDescriptors != null) {
        getLog().debug("Registering all unregistered ArtifactHandlers...");

        if (artifactHandlerManager instanceof DefaultArtifactHandlerManager) {
            Set<String> existingHints = ((DefaultArtifactHandlerManager) artifactHandlerManager)
                    .getHandlerTypes();
            if (existingHints != null) {
                for (String hint : existingHints) {
                    handlerDescriptors.remove(hint);
                }
            }
        }

        if (handlerDescriptors.isEmpty()) {
            getLog().debug("All ArtifactHandlers are registered. Continuing...");
        } else {
            Map<String, ArtifactHandler> unregisteredHandlers = new HashMap<String, ArtifactHandler>(
                    handlerDescriptors.size());

            for (String hint : handlerDescriptors.keySet()) {
                try {
                    unregisteredHandlers.put(hint,
                            (ArtifactHandler) session.lookup(ArtifactHandler.ROLE, hint));
                    getLog().info("Adding ArtifactHandler for: " + hint);
                } catch (ComponentLookupException e) {
                    getLog().warn("Failed to lookup ArtifactHandler with hint: " + hint + ". Reason: "
                            + e.getMessage(), e);
                }
            }

            artifactHandlerManager.addHandlers(unregisteredHandlers);
        }
    }

    getLog().debug("...done.\nSetting ArtifactHandler on project-artifact: " + project.getId() + "...");

    Set<Artifact> artifacts = new HashSet<Artifact>();
    artifacts.add(project.getArtifact());

    Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
    if (dependencyArtifacts != null && !dependencyArtifacts.isEmpty()) {
        artifacts.addAll(dependencyArtifacts);
    }

    for (Artifact artifact : artifacts) {
        String type = artifact.getType();
        ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(type);

        getLog().debug("Artifact: " + artifact.getId() + "\nType: " + type + "\nArtifactHandler extension: "
                + handler.getExtension());

        artifact.setArtifactHandler(handler);
    }

    getLog().debug("...done.");
}

From source file:de.zalando.mojo.aspectj.CompilerMojoTestBase.java

License:Open Source License

/**
 * /*from   w w w. j  a v  a2s. c o  m*/
 */
protected void setUp() throws Exception {
    // prepare plexus environment
    super.setUp();

    ajcMojo.project = project;
    String temp = new File(".").getAbsolutePath();
    basedir = temp.substring(0, temp.length() - 2) + "/src/test/projects/" + getProjectName() + "/";
    project.getBuild().setDirectory(basedir + "/target");
    project.getBuild().setOutputDirectory(basedir + "/target/classes");
    project.getBuild().setTestOutputDirectory(basedir + "/target/test-classes");
    project.getBuild().setSourceDirectory(basedir + "/src/main/java");
    project.getBuild().setTestSourceDirectory(basedir + "/src/test/java");
    project.addCompileSourceRoot(project.getBuild().getSourceDirectory());
    project.addTestCompileSourceRoot(project.getBuild().getTestSourceDirectory());
    ajcMojo.basedir = new File(basedir);

    setVariableValueToObject(ajcMojo, "outputDirectory", new File(project.getBuild().getOutputDirectory()));

    ArtifactHandler artifactHandler = new MockArtifactHandler();
    Artifact artifact = new MockArtifact("dill", "dall");
    artifact.setArtifactHandler(artifactHandler);
    project.setArtifact(artifact);
    project.setDependencyArtifacts(Collections.EMPTY_SET);

}

From source file:guru.nidi.maven.tools.MavenUtil.java

License:Apache License

public static ArtifactResolutionResult resolveArtifact(MavenSession session, RepositorySystem repository,
        Artifact artifact, boolean transitive, ArtifactFilter resolutionFilter) {
    artifact.setArtifactHandler(new DefaultArtifactHandler(artifact.getType()));
    ArtifactResolutionRequest request = new ArtifactResolutionRequest().setArtifact(artifact)
            .setResolveRoot(true).setServers(session.getRequest().getServers())
            .setMirrors(session.getRequest().getMirrors()).setProxies(session.getRequest().getProxies())
            .setLocalRepository(session.getLocalRepository())
            .setRemoteRepositories(session.getRequest().getRemoteRepositories())
            .setResolveTransitively(transitive).setCollectionFilter(resolutionFilter)
            .setResolutionFilter(resolutionFilter);
    //.setListeners(Arrays.<ResolutionListener>asList(new DebugResolutionListener(new ConsoleLogger())));
    return repository.resolve(request);
}

From source file:org.apache.archiva.converter.artifact.LegacyToDefaultConverter.java

License:Apache License

private boolean copyArtifact(Artifact artifact, ArtifactRepository targetRepository,
        FileTransaction transaction) throws ArtifactConversionException {
    File sourceFile = artifact.getFile();

    if (sourceFile.getAbsolutePath().indexOf("/plugins/") > -1) //$NON-NLS-1$
    {//  ww w  .  j a  va 2s .c  o m
        artifact.setArtifactHandler(artifactHandlerManager.getArtifactHandler("maven-plugin")); //$NON-NLS-1$
    }

    File targetFile = new File(targetRepository.getBasedir(), targetRepository.pathOf(artifact));

    boolean result = true;
    try {
        boolean matching = false;
        if (!force && targetFile.exists()) {
            matching = FileUtils.contentEquals(sourceFile, targetFile);
            if (!matching) {
                addWarning(artifact, Messages.getString("failure.target.already.exists")); //$NON-NLS-1$
                result = false;
            }
        }
        if (result) {
            if (force || !matching) {
                if (testChecksums(artifact, sourceFile)) {
                    transaction.copyFile(sourceFile, targetFile, digesters);
                } else {
                    result = false;
                }
            }
        }
    } catch (IOException e) {
        throw new ArtifactConversionException(Messages.getString("error.copying.artifact"), e); //$NON-NLS-1$
    }
    return result;
}

From source file:org.apache.felix.bundleplugin.BundlePlugin.java

License:Apache License

protected void execute(MavenProject currentProject, Map originalInstructions, Properties properties,
        Jar[] classpath) throws MojoExecutionException {
    try {//from   w  w  w . j  a va  2 s.  c om
        File jarFile = new File(getBuildDirectory(), getBundleName(currentProject));

        Builder builder = buildOSGiBundle(currentProject, originalInstructions, properties, classpath);

        List errors = builder.getErrors();
        List warnings = builder.getWarnings();

        for (Iterator w = warnings.iterator(); w.hasNext();) {
            String msg = (String) w.next();
            getLog().warn("Warning building bundle " + currentProject.getArtifact() + " : " + msg);
        }
        for (Iterator e = errors.iterator(); e.hasNext();) {
            String msg = (String) e.next();
            getLog().error("Error building bundle " + currentProject.getArtifact() + " : " + msg);
        }

        if (errors.size() > 0) {
            String failok = builder.getProperty("-failok");
            if (null == failok || "false".equalsIgnoreCase(failok)) {
                jarFile.delete();

                throw new MojoFailureException("Error(s) found in bundle configuration");
            }
        }

        // attach bundle to maven project
        jarFile.getParentFile().mkdirs();
        builder.getJar().write(jarFile);

        Artifact mainArtifact = currentProject.getArtifact();

        // workaround for MNG-1682: force maven to install artifact using the "jar" handler
        mainArtifact.setArtifactHandler(m_artifactHandlerManager.getArtifactHandler("jar"));

        if (null == classifier || classifier.trim().length() == 0) {
            mainArtifact.setFile(jarFile);
        } else {
            m_projectHelper.attachArtifact(currentProject, jarFile, classifier);
        }

        if (unpackBundle) {
            unpackBundle(jarFile);
        }

        if (manifestLocation != null) {
            File outputFile = new File(manifestLocation, "MANIFEST.MF");

            try {
                Manifest manifest = builder.getJar().getManifest();
                ManifestPlugin.writeManifest(manifest, outputFile);
            } catch (IOException e) {
                getLog().error("Error trying to write Manifest to file " + outputFile, e);
            }
        }

        // cleanup...
        builder.close();
    } catch (MojoFailureException e) {
        getLog().error(e.getLocalizedMessage());
        throw new MojoExecutionException("Error(s) found in bundle configuration", e);
    } catch (Exception e) {
        getLog().error("An internal error occurred", e);
        throw new MojoExecutionException("Internal error in maven-bundle-plugin", e);
    }
}

From source file:org.apache.hyracks.maven.license.SourcePointerResolver.java

License:Apache License

private void ensureCDDLSourcesPointer(Collection<Project> projects, ArtifactRepository central,
        ArtifactResolutionRequest request) throws ProjectBuildingException, IOException {
    for (Project p : projects) {
        if (p.getSourcePointer() != null) {
            continue;
        }/*  w  w w. j av  a2 s.com*/
        mojo.getLog().debug("finding sources for artifact: " + p);
        Artifact sourcesArtifact = new DefaultArtifact(p.getGroupId(), p.getArtifactId(), p.getVersion(),
                Artifact.SCOPE_COMPILE, "jar", "sources", null);
        MavenProject mavenProject = mojo.resolveDependency(sourcesArtifact);
        sourcesArtifact.setArtifactHandler(mavenProject.getArtifact().getArtifactHandler());
        final ArtifactRepository localRepo = mojo.getSession().getLocalRepository();
        final File marker = new File(localRepo.getBasedir(), localRepo.pathOf(sourcesArtifact) + ".oncentral");
        final File antimarker = new File(localRepo.getBasedir(),
                localRepo.pathOf(sourcesArtifact) + ".nocentral");
        boolean onCentral;
        if (marker.exists() || antimarker.exists()) {
            onCentral = marker.exists();
        } else {
            request.setArtifact(sourcesArtifact);
            ArtifactResolutionResult result = mojo.getArtifactResolver().resolve(request);
            mojo.getLog().debug("result: " + result);
            onCentral = result.isSuccess();
            if (onCentral) {
                FileUtils.touch(marker);
            } else {
                FileUtils.touch(antimarker);
            }
        }
        StringBuilder noticeBuilder = new StringBuilder("You may obtain ");
        noticeBuilder.append(p.getName()).append(" in Source Code form code here:\n");
        if (onCentral) {
            noticeBuilder.append(central.getUrl()).append("/").append(central.pathOf(sourcesArtifact));
        } else {
            mojo.getLog().warn("Unable to find sources in 'central' for " + p
                    + ", falling back to project url: " + p.getUrl());
            noticeBuilder.append(p.getUrl() != null ? p.getUrl() : "MISSING SOURCE POINTER");
        }
        p.setSourcePointer(noticeBuilder.toString());
    }
}

From source file:org.apache.nifi.NarProvidedDependenciesMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*w  w w  .j av a2  s.c  om*/
        // find the nar dependency
        Artifact narArtifact = null;
        for (final Artifact artifact : project.getDependencyArtifacts()) {
            if (NAR.equals(artifact.getType())) {
                // ensure the project doesn't have two nar dependencies
                if (narArtifact != null) {
                    throw new MojoExecutionException("Project can only have one NAR dependency.");
                }

                // record the nar dependency
                narArtifact = artifact;
            }
        }

        // ensure there is a nar dependency
        if (narArtifact == null) {
            throw new MojoExecutionException("Project does not have any NAR dependencies.");
        }

        // build the project for the nar artifact
        final ProjectBuildingRequest narRequest = new DefaultProjectBuildingRequest();
        narRequest.setRepositorySession(repoSession);
        final ProjectBuildingResult narResult = projectBuilder.build(narArtifact, narRequest);

        // get the artifact handler for excluding dependencies
        final ArtifactHandler narHandler = excludesDependencies(narArtifact);
        narArtifact.setArtifactHandler(narHandler);

        // nar artifacts by nature includes dependencies, however this prevents the
        // transitive dependencies from printing using tools like dependency:tree.
        // here we are overriding the artifact handler for all nars so the
        // dependencies can be listed. this is important because nar dependencies
        // will be used as the parent classloader for this nar and seeing what
        // dependencies are provided is critical.
        final Map<String, ArtifactHandler> narHandlerMap = new HashMap<>();
        narHandlerMap.put(NAR, narHandler);
        artifactHandlerManager.addHandlers(narHandlerMap);

        // get the dependency tree
        final DependencyNode root = dependencyTreeBuilder.buildDependencyTree(narResult.getProject(),
                localRepository, null);

        // write the appropriate output
        DependencyNodeVisitor visitor = null;
        if ("tree".equals(mode)) {
            visitor = new TreeWriter();
        } else if ("pom".equals(mode)) {
            visitor = new PomWriter();
        }

        // ensure the mode was specified correctly
        if (visitor == null) {
            throw new MojoExecutionException(
                    "The specified mode is invalid. Supported options are 'tree' and 'pom'.");
        }

        // visit and print the results
        root.accept(visitor);
        getLog().info("--- Provided NAR Dependencies ---\n\n" + visitor.toString());
    } catch (DependencyTreeBuilderException | ProjectBuildingException e) {
        throw new MojoExecutionException("Cannot build project dependency tree", e);
    }
}

From source file:org.codehaus.mojo.jboss.packaging.AbstractPackagingMojo.java

License:Apache License

/**
 * Generates the packaged archive./*from  w  ww  .j  a v  a 2  s.  c  o m*/
 * 
 * @throws MojoExecutionException if there is a problem
 */
protected void performPackaging() throws MojoExecutionException {

    ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler(getArtifactType());
    String extension = artifactHandler.getExtension();
    String type = getArtifactType();

    final File archiveFile = calculateFile(outputDirectory, archiveName, classifier, extension);

    // generate archive file
    getLog().debug("Generating JBoss packaging " + archiveFile.getAbsolutePath());
    MavenArchiver archiver = new MavenArchiver();
    archiver.setArchiver(jarArchiver);
    archiver.setOutputFile(archiveFile);
    try {
        jarArchiver.addDirectory(getPackagingDirectory());
        if (manifest != null) {
            jarArchiver.setManifest(manifest);
        }
        archiver.createArchive(getProject(), archive);
    } catch (Exception e) {
        throw new MojoExecutionException("Problem generating archive file.", e);
    }

    // If there is a classifier, then this archive is not the primary project artifact.
    if (classifier != null && !classifier.equals("")) {
        primaryArtifact = false;
    }

    if (primaryArtifact) {
        Artifact artifact = project.getArtifact();
        artifact.setFile(archiveFile);
        artifact.setArtifactHandler(artifactHandler);
    } else {
        projectHelper.attachArtifact(project, type, classifier, archiveFile);
    }
}

From source file:org.hardisonbrewing.maven.cxx.msbuild.PackageMojo.java

License:Open Source License

@Override
public final void execute() throws MojoExecutionException, MojoFailureException {

    File file;/*from  w  ww  .  j ava 2s.co  m*/

    if (!PropertiesService.hasXapOutput()) {
        StringBuffer filePath = new StringBuffer();
        filePath.append(TargetDirectoryService.getBinDirectoryPath());
        filePath.append(File.separator);
        filePath.append(PropertiesService.getBuildSetting(MSBuildService.BUILD_ASSEMBLY_NAME));
        filePath.append(".dll");
        file = new File(filePath.toString());
    } else {
        StringBuffer filePath = new StringBuffer();
        filePath.append(TargetDirectoryService.getBinDirectoryPath());
        filePath.append(File.separator);
        filePath.append(PropertiesService.getBuildSetting(MSBuildService.BUILD_XAP_FILENAME));
        file = new File(filePath.toString());
    }

    MavenProject project = getProject();

    Artifact artifact = project.getArtifact();
    MSBuildArtifactHandler artifactHandler = new MSBuildArtifactHandler(artifact.getArtifactHandler());
    artifactHandler.setExtension(FileUtils.extension(file.getName()));
    artifact.setArtifactHandler(artifactHandler);

    if (classifier == null) {
        project.getArtifact().setFile(file);
    } else {
        projectHelper.attachArtifact(project, file, classifier);
    }
}

From source file:org.hsc.novelSpider.bundleplugin.BundlePlugin.java

License:Apache License

protected void execute(MavenProject currentProject, Map<String, String> originalInstructions,
        Properties properties, Jar[] classpath) throws MojoExecutionException {

    getLog().warn("2 execute ");

    try {/*from www.  j a  va  2 s  .co  m*/
        File jarFile = new File(getBuildDirectory(), getBundleName(currentProject));

        getLog().warn(" jarFile:" + jarFile.getAbsolutePath());

        Builder builder = buildOSGiBundle(currentProject, originalInstructions, properties, classpath);

        boolean hasErrors = reportErrors("Bundle " + currentProject.getArtifact(), builder);
        if (hasErrors) {
            String failok = builder.getProperty("-failok");
            if (null == failok || "false".equalsIgnoreCase(failok)) {
                jarFile.delete();

                throw new MojoFailureException("Error(s) found in bundle configuration");
            }
        }

        // attach bundle to maven project
        jarFile.getParentFile().mkdirs();
        builder.getJar().write(jarFile);

        Artifact mainArtifact = currentProject.getArtifact();

        if ("bundle".equals(mainArtifact.getType())) {
            // workaround for MNG-1682: force maven to install artifact using the "jar" handler
            mainArtifact.setArtifactHandler(m_artifactHandlerManager.getArtifactHandler("jar"));
        }

        if (null == classifier || classifier.trim().length() == 0) {
            mainArtifact.setFile(jarFile);
        } else {
            m_projectHelper.attachArtifact(currentProject, jarFile, classifier);
        }

        if (unpackBundle) {
            unpackBundle(jarFile);
        }

        if (manifestLocation != null) {
            File outputFile = new File(manifestLocation, "MANIFEST.MF");

            try {
                Manifest manifest = builder.getJar().getManifest();
                ManifestPlugin.writeManifest(manifest, outputFile);
            } catch (IOException e) {
                getLog().error("Error trying to write Manifest to file " + outputFile, e);
            }
        }

        // cleanup...
        builder.close();
    } catch (MojoFailureException e) {
        getLog().error(e.getLocalizedMessage(), e);
        throw new MojoExecutionException("Error(s) found in bundle configuration", e);
    } catch (Exception e) {
        getLog().error("An internal error occurred", e);
        throw new MojoExecutionException("OSGI", e);
    }
}