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

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

Introduction

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

Prototype

void setFile(File destination);

Source Link

Usage

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

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    String iarName = project.getArtifactId() + "-" + project.getVersion() + "." + project.getPackaging();
    File iar = new File(project.getBuild().getDirectory(), iarName);
    createIvyArchive(project.getBasedir(), iar);

    Artifact artifact = project.getArtifact();
    artifact.setFile(iar);
    project.setArtifact(artifact);/* w w  w .j a va 2  s . c om*/
    getLog().info("Attached " + artifact.toString() + ".");
}

From source file:ch.sourcepond.maven.plugin.repobuilder.AdditionalArtifact.java

License:Apache License

/**
 * @return//from w  ww  .j a  v a 2s.c  om
 * @throws MojoExecutionException
 */
Artifact toArtifact() throws MojoExecutionException {
    final DefaultArtifactHandler handler = new DefaultArtifactHandler();
    String extension = this.extension;
    if (isBlank(extension)) {
        extension = getFileExtension(file.getAbsolutePath());
    }

    if (isBlank(extension)) {
        throw new MojoExecutionException(
                "No extension specified; either add an extension to the artifact-file, or, specify parameter 'extension'! Invalid config item: "
                        + this);
    }

    handler.setExtension(extension);
    final Artifact artifact = new DefaultArtifact(groupId, artifactId, version, "", handler.getExtension(),
            classifier, handler);
    artifact.setFile(file);
    return artifact;
}

From source file:cn.wanghaomiao.maven.plugin.seimi.SeimiMojo.java

License:Apache License

/**
 * Generates the webapp according to the <tt>mode</tt> attribute.
 *
 * @param warFile the target WAR file/*  w ww.  j a va 2s. c  o  m*/
 * @throws IOException                           if an error occurred while copying files
 * @throws ArchiverException                     if the archive could not be created
 * @throws ManifestException                     if the manifest could not be created
 * @throws DependencyResolutionRequiredException if an error occurred while resolving the dependencies
 * @throws MojoExecutionException                if the execution failed
 * @throws MojoFailureException                  if a fatal exception occurred
 */
private void performPackaging(File warFile) throws IOException, ManifestException,
        DependencyResolutionRequiredException, MojoExecutionException, MojoFailureException {
    getLog().info("Packaging app");

    buildExplodedWebapp(getWebappDirectory());

    TemplateTask templateTask = new TemplateTask(getWebappDirectory(), getLog());
    templateTask.createBinFile();

    MavenArchiver archiver = new MavenArchiver();

    archiver.setArchiver(warArchiver);

    archiver.setOutputFile(warFile);

    // CHECKSTYLE_OFF: LineLength
    getLog().debug("Excluding " + Arrays.asList(getPackagingExcludes()) + " from the generated app archive.");
    getLog().debug("Including " + Arrays.asList(getPackagingIncludes()) + " in the generated app archive.");
    // CHECKSTYLE_ON: LineLength

    warArchiver.addDirectory(getWebappDirectory(), getPackagingIncludes(), getPackagingExcludes());

    //        final File webXmlFile = new File(getWebappDirectory(), "WEB-INF/web.xml");
    //        if (webXmlFile.exists()) {
    //            warArchiver.setWebxml(webXmlFile);
    //        }

    warArchiver.setRecompressAddedZips(isRecompressZippedFiles());

    warArchiver.setIncludeEmptyDirs(isIncludeEmptyDirectories());

    if (!failOnMissingWebXml) {
        getLog().debug("Build won't fail if web.xml file is missing.");
        warArchiver.setExpectWebXml(false);
    }

    // create archive
    archiver.createArchive(getSession(), getProject(), getArchive());

    // create the classes to be attached if necessary
    if (isAttachClasses()) {
        if (isArchiveClasses() && getJarArchiver().getDestFile() != null) {
            // special handling in case of archived classes: MWAR-240
            File targetClassesFile = getTargetClassesFile();
            FileUtils.copyFile(getJarArchiver().getDestFile(), targetClassesFile);
            projectHelper.attachArtifact(getProject(), "jar", getClassesClassifier(), targetClassesFile);
        } else {
            ClassesPackager packager = new ClassesPackager();
            final File classesDirectory = packager.getClassesDirectory(getWebappDirectory());
            if (classesDirectory.exists()) {
                getLog().info("Packaging classes");
                packager.packageClasses(classesDirectory, getTargetClassesFile(), getJarArchiver(),
                        getSession(), getProject(), getArchive());
                projectHelper.attachArtifact(getProject(), "jar", getClassesClassifier(),
                        getTargetClassesFile());
            }
        }
    }

    if (this.classifier != null) {
        projectHelper.attachArtifact(getProject(), "war", this.classifier, warFile);
    } else {
        Artifact artifact = getProject().getArtifact();
        if (primaryArtifact) {
            artifact.setFile(warFile);
        } else if (artifact.getFile() == null || artifact.getFile().isDirectory()) {
            artifact.setFile(warFile);
        }
    }
}

From source file:com.alibaba.citrus.maven.eclipse.base.ide.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Returns the list of project artifacts. Also artifacts generated from referenced projects will be added, but with
 * the <code>resolved</code> property set to true.
 *
 * @return list of projects artifacts// ww w  .j ava  2s .  co m
 * @throws MojoExecutionException if unable to parse dependency versions
 */
private Set getProjectArtifacts() throws MojoExecutionException {
    // [MECLIPSE-388] Don't sort this, the order should be identical to getProject.getDependencies()
    Set artifacts = new LinkedHashSet();

    for (Iterator dependencies = getProject().getDependencies().iterator(); dependencies.hasNext();) {
        Dependency dependency = (Dependency) dependencies.next();

        String groupId = dependency.getGroupId();
        String artifactId = dependency.getArtifactId();
        VersionRange versionRange;
        try {
            versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
        } catch (InvalidVersionSpecificationException e) {
            throw new MojoExecutionException(Messages.getString("AbstractIdeSupportMojo.unabletoparseversion", //$NON-NLS-1$
                    new Object[] { dependency.getArtifactId(), dependency.getVersion(), dependency.getManagementKey(),
                            e.getMessage() }),
                    e);
        }

        String type = dependency.getType();
        if (type == null) {
            type = Constants.PROJECT_PACKAGING_JAR;
        }
        String classifier = dependency.getClassifier();
        boolean optional = dependency.isOptional();
        String scope = dependency.getScope();
        if (scope == null) {
            scope = Artifact.SCOPE_COMPILE;
        }

        Artifact art = getArtifactFactory().createDependencyArtifact(groupId, artifactId, versionRange, type,
                classifier, scope, optional);

        if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
            art.setFile(new File(dependency.getSystemPath()));
        }

        handleExclusions(art, dependency);

        artifacts.add(art);
    }

    return artifacts;
}

From source file:com.atlassian.maven.plugin.clover.CloverInstrumentInternalMojo.java

License:Apache License

/**
 * @param outDir - output directory for temporary artifacts
 *//*w ww.  j a v a  2s.  c  o m*/
private void injectGrover(final File outDir) {
    if (skipGroverJar) {
        getLog().info(
                "Generation of Clover Groovy configuration is disabled. No Groovy instrumentation will occur.");
        return;
    }

    // create the groovy config for Clover's ASTTransformer
    InstrumentationConfig config = new InstrumentationConfig();
    config.setProjectName(this.getProject().getName());
    config.setInitstring(this.resolveCloverDatabase());
    config.setTmpDir(outDir);

    final List<File> includeFiles = calcIncludedFilesForGroovy();
    getLog().debug("Clover including the following files for Groovy instrumentation: " + includeFiles);
    config.setIncludedFiles(includeFiles);
    config.setEnabled(true);
    config.setEncoding(getEncoding());
    //Don't pass in an instance of DistributedCoverage because it can't be deserialised
    //by Grover (ClassNotFoundException within the groovyc compiler)
    config.setDistributedConfig(getDistributedCoverage() == null ? null
            : new DistributedConfig(getDistributedCoverage().getConfigString()));

    try {
        File groverJar = GroovycSupport.extractGroverJar(this.groverJar, false);
        File groverConfigDir = GroovycSupport.newConfigDir(config,
                new File(getProject().getBuild().getOutputDirectory()));
        final Resource groverConfigResource = new Resource();
        groverConfigResource.setDirectory(groverConfigDir.getPath());
        getProject().addResource(groverConfigResource);

        // get the clover artifact, and use the same version number for grover...
        Artifact cloverArtifact = findCloverArtifact(this.pluginArtifacts);
        // add grover to the compilation classpath
        final Artifact groverArtifact = artifactFactory.createBuildArtifact(cloverArtifact.getGroupId(),
                "grover", cloverArtifact.getVersion(), "jar");
        groverArtifact.setFile(groverJar);
        groverArtifact.setScope(Artifact.SCOPE_SYSTEM);
        addArtifactDependency(groverArtifact);
    } catch (IOException e) {
        getLog().error(
                "Could not create Clover Groovy configuration file. No Groovy instrumentation will occur. "
                        + e.getMessage(),
                e);
    }
}

From source file:com.bealearts.livecycle.ArchiveMojo.java

License:Apache License

/**
 * Execute the Mojo//  www .  j  av a2 s . c om
 */
public void execute() throws MojoExecutionException {
    File archive = new File(this.buildDirectory, this.finalName + ".lca");

    try {
        String[] excludes = { "**/*.application" };

        this.zipArchiver.addDirectory(new File(this.buildDirectory, "classes"), null, excludes);
        this.zipArchiver.setDestFile(archive);
        this.zipArchiver.createArchive();
    } catch (Exception e) {
        throw new MojoExecutionException("Error creating archive", e);
    }

    Artifact artifact = this.project.getArtifact();
    artifact.setFile(archive);
}

From source file:com.bluexml.side.Integration.m2.ampMojo.AmpWithAttachementMojo.java

License:Open Source License

/**
 * Generates the webapp according to the <tt>mode</tt> attribute.
 * //from  w w w . j ava2 s.  c om
 * @param pAmpFile
 *            the target AMP file
 * @throws IOException
 * @throws ArchiverException
 * @throws ManifestException
 * @throws DependencyResolutionRequiredException
 * 
 */
protected void performPackaging(File pAmpFile) throws IOException, ArchiverException, ManifestException,
        DependencyResolutionRequiredException, MojoExecutionException, MojoFailureException {
    getLog().info("Packaging Alfresco AMP (" + this.getAmpName() + ")");
    getLog().info("DEBUG: \n" + this.toString());
    this.buildExplodedAmp(this.getAmpDirectory());

    /* create and setup an archiver */
    MavenArchiver vArchiver = new MavenArchiver();
    vArchiver.setArchiver(this.getAmpArchiver());
    vArchiver.setOutputFile(pAmpFile);

    /* setup amp Archiver */
    this.getAmpArchiver().addDirectory(this.getAmpDirectory(), this.getIncludes(), this.getExcludes());

    // create archive
    vArchiver.createArchive(this.getProject(), archive);

    String vClassifier = this.getClassifier();

    if (vClassifier != null) {
        this.getProjectHelper().attachArtifact(this.getProject(), "amp", vClassifier, pAmpFile);
    } else {
        Artifact vArtifact = this.getProject().getArtifact();

        if (this.isPrimaryArtifact()) {
            vArtifact.setFile(pAmpFile);
        } else if (vArtifact.getFile() == null || vArtifact.getFile().isDirectory()) {
            vArtifact.setFile(pAmpFile);
        }
    }
    // create the classes to be attached if necessary
    getLog().info("attached ? :" + isAttachClasses());
    if (isAttachClasses()) {
        getLog().info("attach jar file :getProject()" + getProject());
        getLog().info("attach jar file :type" + "jar");
        getLog().info("attach jar file :vClassifier" + "vClassifier");
        getLog().info("attach jar file :getTargetClassesFile" + getTargetClassesFile());
        getProjectHelper().attachArtifact(getProject(), "jar", getClassesClassifier(), getTargetClassesFile());
    }
}

From source file:com.github.batkinson.plugins.PackMojo.java

License:Apache License

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {

    getLog().debug("starting pack");

    Packer packer = Pack200.newPacker();
    Unpacker unpacker = null;/*  ww  w  . j  a  va  2s  .c om*/

    if (normalizeOnly)
        unpacker = Pack200.newUnpacker();

    String type = "jar.pack";
    if (compress)
        type = "jar.pack.gz";

    Map<String, String> packerProps = packer.properties();

    packerProps.put(Packer.EFFORT, effort);
    packerProps.put(Packer.SEGMENT_LIMIT, segmentLimit);
    packerProps.put(Packer.KEEP_FILE_ORDER, keepFileOrder);
    packerProps.put(Packer.MODIFICATION_TIME, modificationTime);
    packerProps.put(Packer.DEFLATE_HINT, deflateHint);

    if (stripCodeAttributes != null) {
        for (String attributeName : stripCodeAttributes) {
            getLog().debug("stripping " + attributeName);
            packerProps.put(Packer.CODE_ATTRIBUTE_PFX + attributeName, Packer.STRIP);
        }
    }

    if (failOnUnknownAttributes)
        packerProps.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR);

    List<Artifact> artifactsToPack = new ArrayList<Artifact>();

    if (processMainArtifact)
        artifactsToPack.add(project.getArtifact());

    if (includeClassifiers != null && !includeClassifiers.isEmpty()) {
        for (Artifact secondaryArtifact : (List<Artifact>) project.getAttachedArtifacts())
            if ("jar".equals(secondaryArtifact.getType()) && secondaryArtifact.hasClassifier()
                    && includeClassifiers.contains(secondaryArtifact.getClassifier()))
                artifactsToPack.add(secondaryArtifact);
    }

    String action = normalizeOnly ? "normalizing" : "packing";

    getLog().info(action + " " + artifactsToPack.size() + " artifacts");

    for (Artifact artifactToPack : artifactsToPack) {

        File origFile = artifactToPack.getFile();
        File packFile = new File(origFile.getAbsolutePath() + ".pack");
        File zipFile = new File(packFile.getAbsolutePath() + ".gz");

        try {
            JarFile jar = new JarFile(origFile);
            FileOutputStream fos = new FileOutputStream(packFile);

            getLog().debug("packing " + origFile + " to " + packFile);
            packer.pack(jar, fos);

            getLog().debug("closing handles ...");
            jar.close();
            fos.close();

            if (normalizeOnly) {
                getLog().debug("unpacking " + packFile + " to " + origFile);
                JarOutputStream origJarStream = new JarOutputStream(new FileOutputStream(origFile));
                unpacker.unpack(packFile, origJarStream);

                getLog().debug("closing handles...");
                origJarStream.close();

                getLog().debug("unpacked file");
            } else {

                Artifact newArtifact = new DefaultArtifact(artifactToPack.getGroupId(),
                        artifactToPack.getArtifactId(), artifactToPack.getVersionRange(),
                        artifactToPack.getScope(), type, artifactToPack.getClassifier(),
                        new DefaultArtifactHandler(type));

                if (compress) {
                    getLog().debug("compressing " + packFile + " to " + zipFile);
                    GZIPOutputStream zipOut = new GZIPOutputStream(new FileOutputStream(zipFile));
                    IOUtil.copy(new FileInputStream(packFile), zipOut);
                    zipOut.close();
                    newArtifact.setFile(zipFile);
                } else {
                    newArtifact.setFile(packFile);
                }

                if (attachPackedArtifacts) {
                    getLog().debug("attaching " + newArtifact);
                    project.addAttachedArtifact(newArtifact);
                }
            }

            getLog().debug("finished " + action + " " + packFile);

        } catch (IOException e) {
            throw new MojoExecutionException("Failed to pack jar.", e);
        }
    }
}

From source file:com.github.peterjanes.node.NpmPackMojo.java

License:Apache License

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *//*from   ww w.  java 2 s  . c  o m*/
public void execute() throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(outputDirectory);

    List commandArguments = new ArrayList();
    commandArguments.add("pack");
    commandArguments.add("./commonjs");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        getLog().debug("Executing command line: " + commandLine);
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }

        Artifact artifact = mavenProject.getArtifact();
        String fileName = String.format("%s-%s.tgz", artifact.getArtifactId(),
                mavenProject.getProperties().getProperty("node.project.version"));
        artifact.setFile(new File(outputDirectory, fileName));
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.github.zhve.ideaplugin.ArtifactDependencyResolver.java

License:Apache License

/**
 * Convert Dependency to Artifact/*from www  .  ja v a2  s  .  c  o  m*/
 *
 * @param artifactFactory standard Maven's factory to create artifacts
 * @param dependency      dependency
 * @return artifact
 * @throws InvalidVersionSpecificationException if VersionRange is invalid
 */
private Artifact toDependencyArtifact(ArtifactFactory artifactFactory, Dependency dependency)
        throws InvalidVersionSpecificationException {
    // instantiate
    Artifact dependencyArtifact = artifactFactory.createDependencyArtifact(dependency.getGroupId(),
            dependency.getArtifactId(), VersionRange.createFromVersionSpec(dependency.getVersion()),
            dependency.getType(), dependency.getClassifier(),
            dependency.getScope() == null ? Artifact.SCOPE_COMPILE : dependency.getScope(), null,
            dependency.isOptional());

    // apply exclusions is needed
    if (!dependency.getExclusions().isEmpty()) {
        List<String> exclusions = new ArrayList<String>();
        for (Exclusion exclusion : dependency.getExclusions())
            exclusions.add(exclusion.getGroupId() + ":" + exclusion.getArtifactId());
        dependencyArtifact.setDependencyFilter(new ExcludesArtifactFilter(exclusions));
    }

    // additional
    if (Artifact.SCOPE_SYSTEM.equalsIgnoreCase(dependency.getScope()))
        dependencyArtifact.setFile(new File(dependency.getSystemPath()));

    return dependencyArtifact;
}